假设我在我的网站上搜索"Tales of an Ancient Empire"。我的数据库正在做全文搜索,结果出来了。我有这个用于高亮
的函数function sublinhamos($text, $words) {
// explode the phrase in words
$wordsArray = explode(' ', $words);
// loop all searched words
foreach($wordsArray as $word) {
//highlight
$text = str_ireplace($word, "<span class='"highlight'">".strtoupper($word)."</span>", $text, $count);
}
//right trows results
return $text;
}
还不错,但这里的问题是,因为搜索词是"Tales of an Ancient Empire",当str_ireplace找到已经插入的SPAN's时,它会遇到搜索词中的"an",并打破SPAN标签。
我需要高亮来高亮一个单词的部分,所有的单词至少两个字符,但这一切都很好,除了旧的SPAN遇到问题。
有什么想法吗?
首先,我不会使用span。
<mark></mark>
是更好的元素。它的目的是突出显示像这样的文本部分。更多信息请参阅本文。
也可以将数组传递给str_replace,例如:
function sublinhamos($text, $words) {
$wordsArray = array();
$markedWords = array();
// explode the phrase in words
$wordsArray = explode(' ', $words);
foreach ($wordsArray as $k => $word) {
$markedWords[$k]='<mark>'.$word.'</mark>';
}
$text = str_ireplace($wordsArray, $markedWords, $text);
//right trows results
return $text;
}
您可以将其替换为不会被搜索的临时字符串(例如:{{{和}}}),如下所示:
$text = str_ireplace($word, "{{{".strtoupper($word)."}}}", $text, $count);
标记完所有的点击后,你可以简单的替换掉你的span标签中的临时字符串
您可以使用带有负向后看的preg_replace:
$text = preg_replace('/(?<!<sp)(?<!<'/sp)(an)/i', '<span class="highlight">$1</span>', $text);
第一个向后看用于开始span标记,第二个用于结束标记。您可以将它们合并为一个,但不确定。
你试过这样做吗?
$text = preg_replace("|($word)|", "<span class='"highlight'">".strtoupper($word)."</span>", $text, $count);