highlight search result

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
User avatar
ddragas
Forum Contributor
Posts: 445
Joined: Sun Apr 18, 2004 4:01 pm

highlight search result

Post 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
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

User avatar
ddragas
Forum Contributor
Posts: 445
Joined: Sun Apr 18, 2004 4:01 pm

Post by ddragas »

Thank you for quick reply

How to make it not to be case sensitive?
User avatar
Luke
The Ninja Space Mod
Posts: 6424
Joined: Fri Aug 05, 2005 1:53 pm
Location: Paradise, CA

Post 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
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

the basics of what you would need is all detailed in the stickies of the Regex board found on this server.
User avatar
bokehman
Forum Regular
Posts: 509
Joined: Wed May 11, 2005 2:33 am
Location: Alicante (Spain)

Post 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.
User avatar
Ollie Saunders
DevNet Master
Posts: 3179
Joined: Tue May 24, 2005 6:01 pm
Location: UK

Post 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.
User avatar
bokehman
Forum Regular
Posts: 509
Joined: Wed May 11, 2005 2:33 am
Location: Alicante (Spain)

Post 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.
Post Reply