突出显示不区分大小写的关键字


Highlight keyword without case sensitive?

我使用这个成功地突出显示了关键字

 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;
}

然而,它区分大小写。如何在不区分大小写的情况下使其工作?

您似乎对您的解决方案有点困惑,请尝试此方法(适用于任何情况,但可能需要扩展以下关键字的特殊字符):

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;
}

(假设关键字如示例代码中那样以空格分隔)

现在应该可以使用了。它希望关键字是一个中间有空格的字符串。

显然,如果这是在接受用户输入,那么您将需要以某种方式转义该输入。

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