【发布时间】:2012-02-17 20:21:02
【问题描述】:
我一直在为突出显示 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 而不是 Regex 来做到这一点
-
你用javascript遍历DOM吗?如果是这样,您有什么插件可以推荐吗?我只见过一个 php DOM 解析器,它很慢。
-
javascript 或 php.net/dom
-
让我想知道他们是如何创建构造 DOM 树的......也许是正则表达式?
-
@Gordon:这是一个骗子,另一个问题有一个很好的answerIMO。
标签: php search keyword highlight