Php 突出显示功能突出显示单词中的单词
我开发了以下函数来突出显示搜索结果名称Php 突出显示功能突出显示单词中的单词,php,regex,highlight,Php,Regex,Highlight,我开发了以下函数来突出显示搜索结果名称 function highlight($text, $words) { if (!is_array($words)) { $words = preg_split('#\\W+#', $words, -1, PREG_SPLIT_NO_EMPTY); } $regex = '#\\b(\\w*)('; $sep = ''; for
function highlight($text, $words)
{
if (!is_array($words))
{
$words = preg_split('#\\W+#', $words, -1, PREG_SPLIT_NO_EMPTY);
}
$regex = '#\\b(\\w*)(';
$sep = '';
foreach ($words as $word)
{
$regex .= $sep . preg_quote($word, '#');
$sep = '|';
}
$regex .= ')(\\w*)\\b#i';
$text = preg_replace($regex, '\\1<b>\\2</b>\\3', $text);
$text = str_replace("</b> <b>"," ",$text);
return $text;
}
函数突出显示($text,$words)
{
如果(!is_数组($words))
{
$words=preg#u split('#\\W+#',$words,-1,preg#u split#NO#u为空);
}
$regex='\\\b(\\w*)(';
$sep='';
foreach($words作为$word)
{
$regex.=$sep.preg_quote($word,#');
$sep=“|”;
}
$regex.=')(\\w*)\\b#i';
$text=preg_replace($regex,\\1\\2\\3',$text);
$text=str_replace(“,”,$text);
返回$text;
}
我的问题是如果文本是“到此为止”
我在寻找“this is”,它会像这样突出显示:“thisisthe end”,因为“is”这个词也在“this”中
有人知道怎么解决吗
我的第一个想法是只替换空白[空白],但这不是一个好的解决方案,因为句子的第一个单词开头没有空白-(
感谢您的帮助。删除正则表达式开头和结尾的
\w*
:
$regex = '#\\b(';
$sep = '';
foreach ($words as $word)
{
$regex .= $sep . preg_quote($word, '#');
$sep = '|';
}
$regex .= ')\\b#i';
$text = preg_replace($regex, '<b>$1</b>', $text);
$regex='\\\b(';
$sep='';
foreach($words作为$word)
{
$regex.=$sep.preg_quote($word,#');
$sep=“|”;
}
$regex.=')\\b#i';
$text=preg_replace($regex,$1',$text);
突出显示空格cO:“到此结束”编辑:抱歉,我没有看到preg_replace.:-)中的更改,修复了它-非常感谢much@Marv:保留您的str\u替换