Page 1 of 1

highlight search result

Posted: Tue Aug 01, 2006 2:32 pm
by ddragas
Hi all

Can somebody point me in right direction on how to highlight search result (whole word).

Example

$search = "highlight sear";

$recordset = "I would like to highlight some words from search resoults";



Thank you

regards ddragas

Posted: Tue Aug 01, 2006 2:34 pm
by feyd

Posted: Tue Aug 01, 2006 4:01 pm
by ddragas
Thank you for quick reply

How to make it not to be case sensitive?

Posted: Tue Aug 01, 2006 4:05 pm
by Luke
there is a modifier (I'm no regex pro... I think that's what it's called) that does that... uhh I think it's /i

Posted: Tue Aug 01, 2006 4:12 pm
by feyd
the basics of what you would need is all detailed in the stickies of the Regex board found on this server.

Posted: Tue Aug 01, 2006 5:03 pm
by bokehman

Code: Select all

if(!empty($_GET['highlight']))
{
	if(preg_match_all('@[^\W]{3,}@', $_GET['highlight'], $matches))
	{
		$content = preg_replace(
			'~\b('.implode('|', $matches[0]).')\w*\b(?![^<]*[>])~is',
			'<span class="highlight">$0</span>',
			$content
		);
	}		           
}
ddragas wrote:Can somebody point me in right direction on how to highlight search result (whole word).
The code above does that but may lead to unpredictible results like cat highlighting category which may or may not be what you wanted. To stop this behaviour remove the "\w*" from the expession.

Posted: Tue Aug 01, 2006 6:25 pm
by Ollie Saunders
If bokehman's code is good it should surely be added to code snippets.
I haven't tested it but it sure impressed me, nice work bokehman.

Posted: Wed Aug 02, 2006 2:07 am
by bokehman
ole wrote:If bokehman's code is good it should surely be added to code snippets.
I haven't tested it but it sure impressed me, nice work bokehman.
It does work as can be seen here: http://prueba.revistafoto.es/concurso-f ... 1150322401 The only difference is the name of the variable, highlight >> destacar.