Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
465 views
Welcome To Ask or Share your Answers For Others

1 Answer

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

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...