Using preg_replace for google style keyword highlighting
Posted: Mon Sep 23, 2002 8:41 am
Hiya,
I've been messing around with a function to have the keyword search script I've written automatically highlight the search terms used throughout the printed results . . . However, I've run into a bit of a problem when I modified the script for multiple word and boolean searches. The highlighter worked fine when you entered a single word with the old version of the script . . . However, when I made the change to the search query, I seemingly lost the functionality of the highlighter.
Here's the original script prior to the change:
I'd then use ob_start("callback"); to begin the highlighting and ob_end_flush(); to bring it to an end.
After I made the changes to the highlight function in an attempt to accomidate the new search script, highlighting would work fine when you input a single word, but not with multiple words. In the case of multiple words, it would only highlight the first word. Here's the new script:
Of course still using ob_start("callback"); to begin the highlighting and ob_end_flush(); to bring it to an end.
Any idea on how to get the function to highlight all of the search terms entered?
Also, might anyone have an idea on how to use different colors for each search term, possibly based on the terms themselves? (Red background with white text for the word "apple" for example.)
Thanks a whole bunch in advance!
--Tony
I've been messing around with a function to have the keyword search script I've written automatically highlight the search terms used throughout the printed results . . . However, I've run into a bit of a problem when I modified the script for multiple word and boolean searches. The highlighter worked fine when you entered a single word with the old version of the script . . . However, when I made the change to the search query, I seemingly lost the functionality of the highlighter.
Here's the original script prior to the change:
Code: Select all
function callback($buffer) {
global $search;
return preg_replace('|('.quotemeta($search).')|iU',
'<span class=''highlight''>\\1</span>', $buffer);
}After I made the changes to the highlight function in an attempt to accomidate the new search script, highlighting would work fine when you input a single word, but not with multiple words. In the case of multiple words, it would only highlight the first word. Here's the new script:
Code: Select all
function callback($buffer) {
global $search;
$words = explode(' ', $search);
foreach( $words AS $word ){
return preg_replace('|('.quotemeta($word).')|iU',
'<span class=''highlight''>\\1</span>', $buffer);
}
}Any idea on how to get the function to highlight all of the search terms entered?
Also, might anyone have an idea on how to use different colors for each search term, possibly based on the terms themselves? (Red background with white text for the word "apple" for example.)
Thanks a whole bunch in advance!
--Tony