我使用此
成功突出显示了关键字 function highlight($str, $keywords)
{
$keywords2 = $keywords;
$keywords = preg_replace('/\s\s+/', ' ', strip_tags(trim($keywords))); // filter
$str = str_replace($keywords2,"<strong>$keywords2</strong>",$str);
$var = '';
foreach(explode(' ', $keywords) as $keyword)
{
$replacement = "<strong>".$keyword."</strong>";
$var .= $replacement." ";
$str = str_ireplace(" ".$keyword." ", " ".$replacement." ", $str);
$str = str_ireplace(" ".$keyword, " ".$replacement, $str);
}
$str = str_ireplace(rtrim($var), "<strong>".$keywords."</strong>", $str);
return $str;
}
然而,它的情况敏感。如何在没有区分大小写的情况下使其工作?
答案 0 :(得分:2)
您似乎对您的解决方案感到有些困惑,请尝试相反(适用于任何情况,可能需要扩展以下关键字后可用的特殊字符):
function highlightKeywords($str, $keywords) {
$keywordsArray = explode(' ', strip_tags(trim($keywords)));
foreach ($keywordsArray as $keyword) {
$str = preg_replace("/($keyword)([\s\.\,])/i", "<strong>$1</strong>$2", $str);
}
return $str;
}
(假设关键字在示例代码中按空格分隔)
答案 1 :(得分:1)
这应该适合你。它希望关键字是一个字符串,中间有空格。
显然,如果这是用户输入,那么你需要以某种方式逃避该输入。
function highlight($str, $keywords) {
// Convert keywords to an array of lowercase keywords
$keywords = str_replace(' ', ',', $keywords);
$keywordsArray = explode(',', strtolower($keywords));
// if any lowercase version of a word in the string is found in the
// keywords array then wrap that word in <strong> tags in the string
foreach (explode(' ', $str) as $word) {
if (in_array(strtolower($word), $keywordsArray)) {
$str = str_replace("$word ", "<strong>$word</strong> ", $str);
}
}
return $str;
}
$ word var及其替换后的空格是为了防止在关键字出现多次出现时对其进行双重封装。
示例用法:
$str = 'the quick brown fox jumped over Mr Brown the lazy dog';
$keywords = 'the brown fox';
echo highlight($str, $keywords);
将输出:
<strong>the</strong> quick <strong>brown</strong> <strong>fox</strong> jumped over Mr <strong>Brown</strong> <strong>the</strong> lazy dog