0
我一直在HTML或純文本字符串突出的搜索字詞的想法中掙扎。我看到很多例子,只是不起作用,所以這裏是我的破解。請給我一些情況下,這將打破HTML或不會工作。我能想到的唯一兩種情況是:如果在文本字符串中有「>我不是計算機」和格式不正確的html。所以這是代碼。謝謝你,我希望它可以幫助別人
function search_highlight($text,$search_terms)
{
$color = array('#FFFF00','#00FFFF','#FF9900','#00FF00','#CCCCCC','red','grean','orange');
$count = 0;
if (! is_array($search_terms))
{
$search_terms = explode(' ', $search_terms);
}
// Highlight each of the terms
foreach ($search_terms as $term)
{
//skip blank terms that arise from double spaces
if(! $term) continue;
//Regex Explained:
//The regex first matches a word boundary
//Next it matches the search term liternal
//Next it matches a word boundary
//Next is matches, but doesn't include the following regex...
//Anything other than the literals <and> zero or more times
//Next it will match either a < literal or the end of the string
$text = preg_replace('/\b('.preg_quote(trim($term)).')\b(?=[^><]*<|.$)/i', '<span style="background-color:'.$color[$count].'">\1</span>', $text);
//increment counter for new color
$count++;
}
return $text;
}
他們所有人可能不工作的原因是因爲你想用DOM做而不用正則表達式 – Gordon
你用JavaScript來遍歷DOM嗎?如果有,你會建議任何插件?我只看到一個php DOM解析器,它很慢。 – John
無論是JavaScript或http://php.net/dom – Gordon