php – 在搜索中突出显示多个关键字

前端之家收集整理的这篇文章主要介绍了php – 在搜索中突出显示多个关键字前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在使用此代码突出显示搜索关键字:
function highlightWords($string,$word)
 {

        $string = str_replace($word,"<span class='highlight'>".$word."</span>",$string);
    /*** return the highlighted string ***/
    return $string;

 }

 ....

  $cQuote =  highlightWords(htmlspecialchars($row['cQuotes']),$search_result);

但是,这只突出显示一个关键字.如果用户输入多个关键字,则会缩小搜索范围,但不会突出显示任何字词.我怎么能突出一个以上的单词呢?

正则表达式是要走的路!
function highlight($text,$words) {
    preg_match_all('~\w+~',$words,$m);
    if(!$m)
        return $text;
    $re = '~\\b(' . implode('|',$m[0]) . ')\\b~';
    return preg_replace($re,'<b>$0</b>',$text);
}

$text = '
Lorem ipsum dolor sit amet,consectetur adipisicing elit,sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
consequat.
';

$words = 'ipsum labore';

print highlight($text,$words);

要以不区分大小写的方式匹配,请将“i”添加到正则表达式中

$re = '~\\b(' . implode('|',$m[0]) . ')\\b~i';

注意:对于像“ä”这样的非英语字母,结果可能因地区而异.

原文链接:https://www.f2er.com/php/136453.html

猜你在找的PHP相关文章