note 87350 deleted from function.str-ireplace by danbrown
| From: | danbrown@php.net | Date: | Mon, 18 May 2009 14:46:44 +0000 |
| Subject: | note 87350 deleted from function.str-ireplace by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-155679@lists.php.net to get a copy of this message | ||
Note Submitter: dave_st24 at hotmail dot com
----
I found that many highlight string functions failed whilst performing a certain task on one of my
projects.
$search="hi l";
$string="Hi-Level";
Because the str_ireplace function was looping through the two words ('hi' and
'l'), on the second loop it was replace the 'l' in 'class' and
'highlight' (not what you want)
This is what I have come up with
<?php
function highLight($needle,$haystack) {
$needle=trim($needle);
$wordsArray=explode(' ',$needle);
foreach($wordsArray as $key => $word) {
if(strlen(trim($word))!=0)
$haystack=str_ireplace($word,"***$word**",$haystack);
}
$haystack=str_replace("***","<span
class=\"highlight\">",$haystack);
$haystack=str_replace("**","</span>",$haystack);
return $haystack;
}
echo highLight("hi l","Hi-Level");
// returns <span class="highlight">hi</span>-<span
class="highlight">l</span>eve<span
class="highlight">l</span>
function highLight_OLD($needle,$haystack) {
$needle=trim($needle);
$wordsArray=explode(' ',$needle);
foreach($wordsArray as $key => $word) {
if(strlen(trim($word))!=0)
$haystack=str_ireplace($word,"<span
class=\"highlight\">$word</span>",$haystack);
}
return $haystack;
}
echo highLight_OLD($needle,$haystack);
// returns <span c<span class="highlight">l</span>ass="high<span
class="highlight">l</span>ight">hi</span>-<span
class="highlight">l</span>eve<span
class="highlight">l</span>
?>