我正在php中搜索并替换一个字符串。
如果我的示例字符串是
我的名字是Matthew Scott Hailwood
然后,当函数在搜索o
的情况下运行时,输出变为(为了可读性,分为多行)
My name is
Matthew
Sc<span class="highlight">o</span>tt
Hailw<span class="highlight">o</span><span class="highlight">o</span>d
那部分工作得很好。
我的css类有
.highlight{
font-weight: bold;
background-color: yellow;
border: 1px dotted #a9a9a9;
}
这也非常有效。
但在双字母的情况下,例如姓氏中的oo
,中间边界的厚度是其两倍。
我想做的要么是:如果有两个边界,就把中间边界全部去掉,要么更有可能的是把两个边界合二为一。
我的php函数是
function highlight($haystack, $needle,
$wrap_before = '<span class="text_highlight">',
$wrap_after = "</span>"){
if($needle == '')
return $haystack;
$needle = preg_quote($needle);
return preg_replace("/({$needle})/i", $wrap_before."$1".$wrap_after, $haystack);
}
如果使用正则表达式/({$needle}+)/i
,正则表达式将把一组o和一个o匹配在一起。所以你修改后的代码看起来像:
function highlight($haystack, $needle,
$wrap_before = '<span class="text_highlight">',
$wrap_after = "</span>"){
if($needle == '')
return $haystack;
$needle = preg_quote($needle);
return preg_replace("/({$needle}+)/i", $wrap_before."$1".$wrap_after, $haystack);
}
+
匹配一个或多个前一个字符(或组中的字符)。