<?php
$text='Would you be so kind to highlight css-tricks.com in this string?';
$search='css-tricks.com';
echo textHighlight($text,$search);
//Performs a regex-texthighlight
function textHighlight($text,$search,$highlightColor='#0000FF',$casesensitive=false)
{
$modifier=($casesensitive) ? 'i' : '';
//quote search-string, cause preg_replace wouldn't work correctly if chars like $?. were in search-string
$quotedSearch=preg_quote($search,'/');
//generate regex-search-pattern
$checkPattern='/'.$quotedSearch.'/'.$modifier;
//generate regex-replace-pattern
$strReplacement='$0';
return preg_replace($checkPattern,$strReplacement,$text);
}
?>
此代码执行正则表达式替换以添加具有可定义颜色的span标签。可用于区分大小写的替换和不区分大小写的替换。
这不起作用……
你没有使用:$highlightColor
在替换代码中的任何地方……
此致
feha
@feha,你可能太迟了,看不到这个,但我发现了php_manual中preg_replace中的评论——更简单,并且适用于大多数情况
function highlight($haystack,$needle)
{
$haystack=preg_replace("/($needle)/i","<span style='font-weight:bold'>\${1}</span>",$haystack);
return $haystack;
}