note 104027 deleted from function.str-replace by danbrown

From: Date: Wed, 18 May 2011 14:44:24 +0000
Subject: note 104027 deleted from function.str-replace by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-179855@lists.php.net to get a copy of this message
Note Submitter: Kamba_Jeno at from_hungary dot hu ---- hi everyone! many people use str_replace function in cycle to highlight search results like this ->$haystack = str_replace($match, "<b class=\"x1\">$match</b>", $haystack); But what we have to do if someone typing a text what matches our html code like 'class' just becose its do this effect <b <b class=\"x1\">$match</b>=\"x1\">$match</b>. To solve this problem i create the following function what can do escaped replacement. <?php function esc_str_replace($search,$replace,$where){ $block=false; $keylength=strlen($search); $replacelength=strlen($replace); $escape_chars=array($replace[0],$replace[$replacelength-1]); $textlength=strlen($where); $count=0; for($i=0;$i<$textlength;$i++){ //check if($block==false){ //blocking characters $block=($where[$i]==$escape_chars[0])? true:false; } if($block==true){ //unblocking characters if($where[$i]==$escape_chars[1] && $count !=2) {$count++;} if($where[$i]==$escape_chars[1] && $count ==2) {$block=false;$count=0;continue;} } //if we are not in escaped sequence if($block == false){ //use the replace function like str_replace if($where[$i]==$search[0]){ $slice=substr($where,$i,$keylength); if($slice==$search){ $where=substr_replace($where,$replace,$i,$keylength); $i+=$replacelength; $textlength=strlen($where); } } } } return $where; } //and now we can use safely our keyword highlight function function highlightStr($haystack, $needle) { if (strlen($haystack) < 1 || strlen($needle) < 1) { return $haystack; } preg_match_all("/$needle+/i", $haystack, $matches); if (is_array($matches[0]) && count($matches[0]) >= 1) { foreach ($matches[0] as $match) { $haystack = esc_str_replace($match, "<b class=\"x1\">$match</b>", $haystack); } } return $haystack; } //And something useful what we have to do by sorting the keywords with length properties before accept the highlighting. //This must be needed because if first element replaced and this keyword part of the second keyword the whole keyword highlight fail. ?> Greetings from hungary:)

« previous php.notes (#179855) next »