View Full Version : Highlighting search terms in results

10-27-2009, 02:35 PM

I have a search form that returns results, and I'd like to highlight the search term in the results e.g. if the user searched for North, was the word North found in the House Name, or Town, or country etc.

Is there an easier way to do this than checking to see if every word in the returned row matches the search term?

I'm using php and mySQL.

Thanks for your help!


Phil Jackson
10-27-2009, 03:14 PM

function highlight($word, $color, $text)
$word = preg_quote($word, "#");
$text = preg_replace("#".$word."#is", "<span style=\"color:".$color."\">".$word."</span>", $text);
return $text;

$text = "foo bar barfoo foobar";
$text = highlight("foo", "#00CC33", $text);

echo $text;


your welcome