How To Highlight Search Results
Solution 1:
You shouldn't make it too hard for yourself. All you need it to replace every occurrence of a word with the word wrapped in the span with the required style applied. This should work for you:
functionhighlight_word($content, $word, $color) {
$replace = '<span style="background-color: ' . $color . ';">' . $word . '</span>'; // create replacement$content = str_replace( $word, $replace, $content ); // replace contentreturn$content; // return highlighted data
}
functionhighlight_words($content, $words, $colors) {
$color_index = 0; // index of color (assuming it's an array)// loop through wordsforeach( $wordsas$word ) {
$content = highlight_word( $content, $word, $colors[$color_index] ); // highlight word$color_index = ( $color_index + 1 ) % count( $colors ); // get next color index
}
return$content; // return highlighted data
}
// words to find$words = array(
'normal',
'text'
);
// colors to use$colors = array(
'#88ccff',
'#cc88ff'
);
// faking your results_text$results_text = array(
array(
'ab' => 'AB #1',
'cd' => 'Some normal text with normal words isn\'t abnormal at all'
), array(
'ab' => 'AB #2',
'cd' => 'This is another text containing very normal content'
)
);
// loop through results (assuming $output1 is true)foreach( $results_textas$result ) {
$result['cd'] = highlight_words( $result['cd'], $words, $colors );
echo'<fieldset><p>ab: ' . $result['ab'] . '<br />cd: ' . $result['cd'] . '</p></fieldset>';
}
Using Regular Expressions to replace content would do as well, though using str_replace()
is a bit faster.
The functions accepts these arguments:
highlight_word( string, string, string );
highlight_words( string, array, array );
The above example results in:
Solution 2:
By using str_ireplace instead of str_replace, the function will work case insensitive
Solution 3:
I would not use the SQL method. As time goes on, and you have more and more highlighting rules, that will become unmanageable. Also trickier to handle the cases where you need to highlight foo
differently to foobar
, but one contains the other.
Separate your data handling from your formatting.
Post a Comment for "How To Highlight Search Results"