ereg_*
的(POSIX正则表达式)函数是作为deprecated 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的教程。
如果用户搜索“时钟”,'str_ireplace'会将文本中的'Clock'变成'clock'。不是一个好的选择。 – 2010-06-17 22:26:34
好点,我会更新我的答案。 – 2010-06-17 22:27:49
@Pekka,他问大小写不匹配,为什么它不是一个好的选择。它只是.. – 2010-06-17 22:32:21