i\'m using this code to highlight search keywords:
function highlightWords($string, $word)
{
$string = str_replace($word, \"
Assuming the words are entered as a space seperated string you can just use explode
$words = explode(' ', $term);
Although if you want to ensure there are not multiple spaces, you may want to remove them from the string first
$term = preg_replace('/\s+/', ' ', trim($term));
$words = explode(' ', $term);
You do then have to generate a replacement array
$highlighted = array();
foreach ( $words as $word ){
$highlighted[] = "<span class='highlight'>".$word."</span>"
}
Then
str_replace($words, $highlighted, $string);
So putting it togther
function highlightWords($string, $term){
$term = preg_replace('/\s+/', ' ', trim($term));
$words = explode(' ', $term);
$highlighted = array();
foreach ( $words as $word ){
$highlighted[] = "<span class='highlight'>".$word."</span>"
}
return str_replace($words, $highlighted, $string);
}
here is simple function to highlight only match text.
function highlighter_text($text, $words)
{
$split_words = explode( " " , $words );
foreach($split_words as $word)
{
$color = "#e5e5e5";
$text = preg_replace("|($word)|Ui" ,
"<span style=\"background:".$color.";\"><b>$1</b></span>" , $text );
}
return $text;
}
call function