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

问题描述

我使用这个code突出搜索关键词:

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?

推荐答案

常规EX pressions是要走的路!

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键正规前pression

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

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

注:对于非enlish像字母A的结果可能会因区域而异

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

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

09-09 15:08