Re: Re: string highlight

From: Date: Wed, 08 Jun 2005 13:57:22 +0000
Subject: Re: Re: string highlight
References: 1 2 3 4  Groups: php.general 
Request: Send a blank email to php-general+get-216615@lists.php.net to get a copy of this message
John Nichel wrote:
Rory Browne wrote:
On 6/8/05, David Duong <david@forizon.org> wrote:
Sebastian wrote:
i'm looking for a function that can highlight certain search terms in a string. anyone have something already made that i can plugin to my exisiting code? I found a couple but they do not work very well.. some break html code if the string contains the keywords in the html. thanks.
You can use str_replace to "highlight" the search terms. For example, you could use the following code for each search term (this function also accepts arrays, see http://php.net/str_replace): str_replace ($search_term, "<b>$search_term</b>", $body_text);
Bad idea. Very bad idea. for example ( using bold to highlight ): <?pseudo_code $html = "<html><body>I want to hightlight the word body in this text. </body></html>"; $search = "body"; $output = str_replace($search, "<b>$search</b>", $html); // $output == "<html><<b>body</b>>I want to hightlight the word <b>body</b> in this text. </<b>body</b>></html>"; // see what I mean? ?>
Good catch Rory. A regex replace would work better here. $search = "body"; $find = "/\b" . $search . "\b/";
if I were Richard Lynch I would mention that you probably want to backslash your backslashes: $find = "/\\b" . $search . "\\b/"; but then again if I were Richard Lynch I would probably assume that John Nichel knows that kind of thing, therefore I would not bother mentioning it, or would I? what would Richard Lynch say? (no offence Richard!, Im just being playful :-) (btw Richard is right about the backslashing!)
preg_replace ( $find, "<b>" . $search . "</b>", $html );


« previous php.general (#216615) next »