PHP   发布时间:2022-04-01  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了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';

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

大佬总结

以上是大佬教程为你收集整理的php – 在搜索中突出显示多个关键字全部内容,希望文章能够帮你解决php – 在搜索中突出显示多个关键字所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。