不区分大小写,匹配文本中的多个搜索词并将它们包装在 <strong> HTML 标签中

问题描述 投票:0回答:3

我正在尝试在我正在制作的搜索脚本中将搜索词加粗。问题是我无法让它不区分大小写地工作。

function highlight($term,$target){
    $terms = explode(" ", $term);
    
    foreach($terms as $term){
        $result = (eregi_replace($term, "<strong>$term</strong>", $target));
    }
    return $result;
}

这就是我到目前为止所拥有的功能。 PHP.net 上说

eregi_replace()
不区分大小写,但由于某种原因它显然不起作用。

php string replace cpu-word case-insensitive
3个回答
9
投票

ereg_*
(POSIX 正则表达式)函数从 PHP 5.3 开始已弃用,并且很长一段时间以来都没有被建议。最好使用 PCRE (
preg_*
) 函数(例如
preg_replace
)。

您可以通过创建不区分大小写的正则表达式,然后将匹配项包装在

<strong>
标签中来实现此目的:

function highlight($term, $target)
{
  $terms = array_unique(explode(" ", $term)); // we only want to replace each term once
  foreach ($terms as $term)
  {
    $target = preg_replace('/\b(' . preg_quote($term) . ')\b/i', "<strong>$1</strong>", $target);
  }

  return $target;
}

它的作用是首先在 preg_quote

 上调用 
$term
 ,这样如果该术语中的正则表达式中有任何有意义的字符,它们就会被转义,然后创建一个正则表达式来查找包围的该术语按单词边界(
\b
——这样如果这个词是“好”,它就不会匹配“再见”)。该术语包含在括号中,以使正则表达式引擎以其现有形式捕获该术语作为“反向引用”(正则表达式引擎挂起匹配部分的一种方式)。通过指定
i
选项,表达式不区分大小写。最后,它用
<strong>
标签包围的相同反向引用替换所有匹配项。

$string = "The quick brown fox jumped over the lazy dog. The quicker brown fox didn't jump over the lazy dog.";
$terms = "quick fox";
highlight($terms, $string);
// results in: The <strong>quick</strong> brown <strong>fox</strong> jumped over the lazy dog. The quicker brown <strong>fox</strong> didn't jump over the lazy dog.

如果您想要有关正则表达式的优秀教程,请查看 regular-expressions.info 上的教程。


0
投票
function highlight($term,$target)
{
    $terms = explode(" ", $term);

    foreach($terms as $term){
        $target = (str_ireplace($term, "<strong>$term</strong>", $target));
    }
    return $target;
}

0
投票

构建一个动态、不区分大小写的正则表达式模式,尊重单词边界,然后将所有替换内容包装在强标签中。

代码:(演示

$safeWords = array_map('preg_quote', explode(' ', 'hat cat'));
$text = 'Cat in the hat that had cataract surgery';

$regex = '#\b(?:' . implode('|', $safeWords) . ')\b#iu';

echo preg_replace($regex, '<strong>$0</strong>', $text);

输出:

<strong>Cat</strong> in the <strong>hat</strong> that had cataract surgery
© www.soinside.com 2019 - 2024. All rights reserved.