正则表达式突出显示html中的搜索词

时间:2012-01-24 15:24:27

标签: php search keyword highlight

  

可能重复:
  Highlight keywords in a paragraph

我一直在努力用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;
}

1 个答案:

答案 0 :(得分:2)

我会使用DOMDocument类,只需在节点内容上进行纯文本替换,而不是尝试使用ninja正则表达式。