在搜索中突出显示多个关键字 [英] highlight multiple keywords in search

查看:49
本文介绍了在搜索中突出显示多个关键字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用此代码突出显示搜索关键字:

i'm using this code to highlight search keywords:

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

但是,这仅突出显示了一个关键字.如果用户输入多个关键字,则会缩小搜索范围,但不会突出显示任何单词.如何突出显示多个单词?

however, this highlights only one keyword. if the user enters more than one keyword, it will narrow down the search but no word is highlighted. how can i highlight more than one word?

推荐答案

正则表达式是必经之路!

regular expressions is the way to go!

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"

To match in a case-insensitive manner, add 'i' to the regular expression

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

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

NB: for non-enlish letters like "ä" the results may vary depending on the locale.

这篇关于在搜索中突出显示多个关键字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆