Page 1 of 1

Sort of an error with a highlight terms function ala Google.

Posted: Sat Sep 28, 2002 8:13 pm
by TonySWcom
Hiya.

I'm having a bit of a problem with a function I found and heavily modified for my own use that highlights the search terms that a person has entered into a search form. I recently added the ability to do exact phrase searches, but now the highlighter needs to be adjusted accordingly because it tends to highlight things as if they were wildcarded. It's a little hard to explain, so I'll describe what it's doing now and what I want it to do.

First, the function itself:

Code: Select all

function callback($buffer) {
global $search;
if(strstr($search,""")) { 
$word = str_replace(""", "", stripslashes($search));
$buffer = preg_replace('|('.quotemeta($word).')|iU', 
'<span class='highlight'>\1</span>', $buffer);
} else {
$words = explode(' ', $search);
foreach( $words AS $word ){
$buffer = preg_replace('|('.quotemeta($word).')|iU', 
'<span class='highlight'>\1</span>', $buffer);
}
}
return $buffer;
}
It's applied like so:

ob_start("callback"); starts the highlighting and ob_end_flush(); ends it . . .

let's say a person were to search for the word "end".

the highlighter will be applied on the words end, ending, send, etc.

I want it so that it only highlights the exact term that the person has searched for. If a person searches for "fire", it will display the results then the highlighter goes to work and highlights only the word "fire" throughout the results and not the words fireball, hellfire, fired, etc.

Any ideas?

Thanks in advance.

--Tony

Posted: Sat Sep 28, 2002 8:41 pm
by volka
from PCRE # Pattern Syntax
\s
any whitespace character
you may search for patterns like \sfire\s

Posted: Sun Sep 29, 2002 3:14 am
by TonySWcom
volka wrote:from PCRE # Pattern Syntax
\s
any whitespace character
you may search for patterns like \sfire\s
Thanks, but it doesn't really seem to work very well.

I tried your example pattern and it still highlights like before. For the word "and", it will highlight like:

and, andy, sand

instead of just and which is what I am aiming for.

unless there is a very specific way I'm supposed to implement this with my code, I don't think that's what I am looking for.

Any other ideas? Possibly using a different string function or pcre function?

Thanks.

--Tony

Posted: Sun Sep 29, 2002 3:59 am
by twigletmac
Instead of \s try \b, IIRC that will match complete words only.

Mac

GOAAAAAAAALLLLLLL!!!!

Posted: Sun Sep 29, 2002 4:09 am
by TonySWcom
Yes, \b does the job perfectly! Thank you so much. I think it's safe to say I've completed this project once and for all . . . Or until I get another wacky idea to attempt to implement into this keyword search I'm building. :wink: