Making keywords bold

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
Luke
The Ninja Space Mod
Posts: 6424
Joined: Fri Aug 05, 2005 1:53 pm
Location: Paradise, CA

Making keywords bold

Post by Luke »

OK, I came up with this to bold the searched keywords in a database search...

Code: Select all

function highlight($row, $keywords){
		foreach($row as $key => $val){
			$highlight = "<b>$keywords</b>";
			$row[$key] = str_ireplace($keywords, $highlight, $val);
		}
		return $row;
	}
It finds the words regardless of their case, but if the original word is capitalized... it replaces it with lower case words... how do I fix this??
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

regex..

Code: Select all

function highlight($row, $keywords){
        foreach($row as $key => $val){
            $row[$key] = preg_replace('#\b('.implode('|',array_map(createfunction('$a','return preg_quote($a,\'#\');'),$keywords)).')\b#','<b>\1</b>',$val);
        }
Charles256
DevNet Resident
Posts: 1375
Joined: Fri Sep 16, 2005 9:06 pm

Post by Charles256 »

User avatar
twigletmac
Her Royal Site Adminness
Posts: 5371
Joined: Tue Apr 23, 2002 2:21 am
Location: Essex, UK

Post by twigletmac »

In case anyone wonders - preg_*() functions are much better than ereg_*() functions...

Mac
User avatar
Ambush Commander
DevNet Master
Posts: 3698
Joined: Mon Oct 25, 2004 9:29 pm
Location: New Jersey, US

Post by Ambush Commander »

But if you wonder, don't listen to any of us and benchmark it yourself.
Post Reply