【问题标题】:Regex highlight search terms in html [duplicate]正则表达式突出显示html中的搜索词[重复]
【发布时间】:2012-02-17 20:21:02
【问题描述】:

可能重复:
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;
}

【问题讨论】:

  • 所有这些可能都不起作用的原因是因为你想用 DOM 而不是 Regex 来做到这一点
  • 你用javascript遍历DOM吗?如果是这样,您有什么插件可以推荐吗?我只见过一个 php DOM 解析器,它很慢。
  • javascript 或 php.net/dom
  • 让我想知道他们是如何创建构造 DOM 树的......也许是正则表达式?
  • @Gordon:这是一个骗子,另一个问题有一个很好的answerIMO。

标签: php search keyword highlight


【解决方案1】:

我会为此使用DOMDocument 类,并简单地对节点内容进行纯文本替换,而不是尝试提出一个忍者正则表达式。

【讨论】:

  • 基于 Gordon 的 cmets 和您的评论,我将使用 DOM 方法,但使用 javascript 可以节省一些交付时间。感谢您的洞察力。
猜你喜欢
  • 2021-06-01
  • 2011-08-20
  • 1970-01-01
  • 1970-01-01
  • 2021-01-24
  • 2012-01-13
  • 1970-01-01
  • 1970-01-01
  • 2017-05-11
相关资源
最近更新 更多