Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

highlight multiple keywords in search

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?

like image 907
input Avatar asked May 03 '10 11:05

input


3 Answers

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.

like image 149
user187291 Avatar answered Oct 14 '22 21:10

user187291


PHP > 5.3.0, try preg_filter()

/**
 * Highlighting matching string
 * @param   string  $text           subject
 * @param   string  $words          search string
 * @return  string  highlighted text
 */
public function highlight($text, $words) {
    $highlighted = preg_filter('/' . preg_quote($words, '/') . '/i', '<b><span class="search-highlight">$0</span></b>', $text);
    if (!empty($highlighted)) {
        $text = $highlighted;
    }
    return $text;
}
like image 37
goldsky Avatar answered Oct 14 '22 19:10

goldsky


Assuming the words are entered as a space seperated string you can just use explode

$words = explode(' ', $term);

Although if you want to ensure there are not multiple spaces, you may want to remove them from the string first

$term = preg_replace('/\s+/', ' ', trim($term));
$words = explode(' ', $term);

You do then have to generate a replacement array

$highlighted = array();
foreach ( $words as $word ){
    $highlighted[] = "<span class='highlight'>".$word."</span>"
}

Then

str_replace($words, $highlighted, $string);

So putting it togther

function highlightWords($string, $term){
    $term = preg_replace('/\s+/', ' ', trim($term));
    $words = explode(' ', $term);

    $highlighted = array();
    foreach ( $words as $word ){
        $highlighted[] = "<span class='highlight'>".$word."</span>"
    }

    return str_replace($words, $highlighted, $string);
}
like image 36
Yacoby Avatar answered Oct 14 '22 19:10

Yacoby