【发布时间】:2015-05-13 01:00:20
【问题描述】:
我开发了以下功能来突出显示搜索结果名称。
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;
}
我的问题是,如果文本是“This is the end” 我正在寻找“this is”,它会像这样突出显示:“this is the end”,因为“is”这个词也在“this”中。
有人知道如何解决这个问题吗?
我的第一个想法是只替换 whitespace[whitespace] 但这不是一个好的解决方案,因为句子中的第一个单词在开头没有空格。 :-(
感谢您的帮助。
【问题讨论】: