Using preg_replace for google style keyword highlighting

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
TonySWcom
Forum Newbie
Posts: 6
Joined: Mon Sep 23, 2002 8:41 am
Contact:

Using preg_replace for google style keyword highlighting

Post by TonySWcom »

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:

Code: Select all

function callback($buffer) {
global $search;
return preg_replace('|('.quotemeta($search).')|iU', 
'<span class=''highlight''>\\1</span>', $buffer);
&#125;
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:

Code: Select all

function callback($buffer) &#123;
global $search;
$words = explode(' ', $search);
foreach( $words AS $word )&#123;
return preg_replace('|('.quotemeta($word).')|iU', 
'<span class=''highlight''>\\1</span>', $buffer);
&#125;
&#125;
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
User avatar
Takuma
Forum Regular
Posts: 931
Joined: Sun Aug 04, 2002 10:24 am
Location: UK
Contact:

Post by Takuma »

How about say you have a array containing lots of colours e.g.

Code: Select all

&lt;?php
$colours = new Array(1 =&gt; "blue", 2 =&gt; "red", 3 =&gt; "green");
?&gt;
Then assign a colour for each element.
Post Reply