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?
Splits your search query up into words, then highlight each words separately.
It might work out better to perform the highlighting in javascript though. jQuery's "contains" selector will probably help avoid problems of replacing markup elements as you go...
http://api.jquery.com/contains-selector/
Assuming the words are entered as a space seperated string you can just use explode
Although if you want to ensure there are not multiple spaces, you may want to remove them from the string first
You do then have to generate a replacement array
Then
So putting it togther
as suggested by user187291, just change following code in order to get text highlighted with yellow background.
Highlight multiple keywords in search including umlauts
I've used the regex written before and replaced
\w
with[A-Za-z0-9_äöüÄÖÜ]
. As you see I added the umlautsäöüÄÖÜ
. I also have removed the\b
so it will match any appearance of the search term.Example
search term:
Su shamp
text:
Sun shiny shampoo
result:
Sun shiny shampoo
The code I've used:
here is simple function to highlight only match text.
call function
The other solutions may be case-insensitive in finding the highlight terms, but do not preserve their case of the original string. So searching for "st" will find "ST" but highlight it as "st", the search term.
I use the following. It first forms the replace array, and then uses str_replace() with array parameters - which avoids recursion.