簡體   English   中英

使用正則表達式突出顯示PHP中的搜索詞,而不會破壞錨標記

[英]Highlight Search Terms in PHP without breaking anchor tags using regex

我正在網站上搜索一些數據庫搜索結果,並試圖在返回的結果中突出顯示與搜索到的詞相匹配的詞。 下面是我到目前為止(在php中):

$highlight = trim($highlight);
if(preg_match('|\b(' . $highlight . ')\b|i', $str_content))
{
    $str_content = preg_replace('|\b(' . $highlight. ')(?!["\'])|i', "<span class=\"highlight\">$1</span>", 
    $str_break;
}

這樣做的缺點是,如果我的搜索字詞也顯示在url永久鏈接中,則返回的結果會將跨度插入href屬性,並破壞定位標記。 無論如何,我的正則表達式中是否有將“任何”信息從出現在開始和結束HTML標記之間的搜索結果中排除的信息?

我知道我可以使用strip_tags()函數並將結果以純文本格式吐出,但是如果不需要的話,我寧願不這樣做。

不要嘗試使用正則表達式解析HTML:
RegEx匹配XHTML自包含標簽以外的打開標簽

試試類似PHP Simple HTML DOM的東西。

<?php
// get DOM
$html = file_get_html('http://www.google.com/search?q=hello+kitty');

// ensure this is properly sanitized.
$term = trim($term);

// highlight $term in all <div class="result">...</div> elements
foreach($html->find('div.result') as $e){
   echo str_replace($term, '<span class="highlight">'.$term.'</span>', $e->plaintext);
}
?>

注意:這不是一個精確的解決方案,因為我不知道您的HTML外觀如何,但這應該使您幾乎步入正軌。

我認為斷言是您要尋找的。

我最終選擇了這條路線,到目前為止,這種路線在這種情況下效果很好。

<?php

if(preg_match('|\b(' . $term . ')\b|i', $str_content))
{
    $str_content = strip_tags($str_content);
    $str_content = preg_replace('|\b(' . $term . ')(?!["\'])|i', "<span class=\"highlight\">$1</span>", $str_content);
    $str_content = preg_replace('|\n[^<]+|', '</p><p>', $str_content);
    break;
}

?>

它仍然是html編碼的,但是現在無需html標簽就更容易解析

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM