Highlight Search Terms in Text
Login or Register to Bookmark this snippet
This function searches the text for words supplied and wraps the word in a <span class="highlight"> tag. Use CSS to apply bold and background color formatting on your page.
<?php
function HighlightTerms($text_string,$keywords) {
//this function searches for words from the keywords, and finds matches in the text,
//and highlights (bolds) them. like google does.
// $text_sting: the text from which you want to highlight and return...
// $keywords: either string or array or words that should be highlighted in the text.
//explode the keywords
$keywords =
explode(" ",
$keywords);
}
//find matches
for ($x=0;$x<count($keywords);$x++) {
if (strlen($keywords[$x]) >
1) {
for ($y=0;$y<count($items);$y++) {
if (isset($items[$y][0])) {
$text_string =
str_replace($items[$y][0],
'<span class="highlight">' .
$items[$y][0] .
'</span>',
$text_string);
}
}
}
}
return $text_string;
}
?>
Added by JC on 11th November, 2007
There are no comments about this snippet.
You must be registered and logged in to post a comment.
Login here to post a comment