Possible Duplicate:
Highlight keywords in a paragraph
I have been struggling with the idea of highlighting search terms in html or pure text strings. I have seen many examples that just don't work so here is my crack at it. Please give me some cases that this will break the html or won't work. The only two case that I can come up with are: if there is a > within the text string such as, "I am > than a computer" and ill formatted html. So here's the code. Thank you and I hope it helps someone
function search_highlight($text,$search_terms)
{
$color = array('#FFFF00','#00FFFF','#FF9900','#00FF00','#CCCCCC','red','grean','orange');
$count = 0;
if ( ! is_array($search_terms))
{
$search_terms = explode(' ', $search_terms);
}
// Highlight each of the terms
foreach ($search_terms as $term)
{
//skip blank terms that arise from double spaces
if( ! $term) continue;
//Regex Explained:
//The regex first matches a word boundary
//Next it matches the search term liternal
//Next it matches a word boundary
//Next is matches, but doesn't include the following regex...
//Anything other than the literals < and > zero or more times
//Next it will match either a < literal or the end of the string
$text = preg_replace('/\b('.preg_quote(trim($term)).')\b(?=[^><]*<|.$)/i', '<span style="background-color:'.$color[$count].'">\1</span>', $text);
//increment counter for new color
$count++;
}
return $text;
}