Sometimes it can be really usefull for a visitor to have the terms he serached for highlighted. The following snippet is using a simple regular expression to find words in a phrase and highlight them.
function highlight($sString, $aWords) {
if (!is_array ($aWords) || empty ($aWords) || !is_string ($sString)) {
return false;
}
$sWords = implode ('|', $aWords);
return preg_replace ('@\b('.$sWords.')\b@si', '<strong style="background-color:yellow">$1</strong>', $sString);
}
Usage
The function take two parameters: The first is the phrase and the second is an array of words to be highlighted in the phrase.
echo highlight('Highlight the words PHP and snippets in a phrase', array ('php', 'snippets'));
Words aren’t case sensitive.

9 Comments
Exactly what I need! Where should I add that piece of code? to my functions.php?
If you plan to use it within WordPress, yes.
You’ve forgot about closed strong tag
Sorry. The syntax highlighter ate it :/
your a legend jean
How can I highlight string with html on it without highlightin the html, and therefore breaking the html?
This function can be greatly improved, it’s longer than necessary, has no color options via parameter and you’re forced to use an array even if you only want to highlight one word.
Whilst it works perfectly fine, it is impractical so i wrote an improved version which you can see here:
http://webgadgetfinder.com/archives/283
Enjoy!
Regards,
Dan
Escape $sWords with preg_quote will be better :
return preg_replace ('@\b('.preg_quote($sWords).')\b@si', '$1', $sString);
So good. Thanks man !
2 Trackbacks
[...] This post was mentioned on Twitter by Jean-Baptiste Jung and others. Jean-Baptiste Jung said: RT @phpsnippets: PHP Snippet: Highlights words in a phrase http://bit.ly/aV36kb #php [...]
[...] '<strong style="background-color:yellow">$1</strong>', $sString); }Source: http://www.phpsnippets.info/highlights-words-in-a-phraseGet your average Feedburner subscribersRecently, Feedburner counts had lots of problems and [...]