Monday, July 11, 2011

PHP highlight search keywords

Sometimes we may wish to highlight the search keywords(search terms) in the searching result.

For example, there is a string "A cat is a mini tiger. Actually, cat and tiger belong to the same category". We may want to highlight all the 'cat' within this string, but we obviously don't want to highlight the 'cat' in 'category'.

Here is the result of our highlighting.

A cat is a mini tiger. Actually, cat and tiger belong to the same category

Here is how we can do it:

$string = "A cat is a mini tiger. Actually, cat and tiger belong to the same category";
$match  = "cat";
$string = preg_replace("/(\b)($match)(\b)/i", "$1<u>$2</u>$3", $string);

\b is word boundary. This will ensure we only match the 'cat' as a whole word. It can match "cat" or "cat's", but it won't match "category".

If we want to make the word italic. We can do:
$string = preg_replace("/(\b)($match)(\b)/i", "$1<i>$2</i>$3", $string);

No comments: