note 87350 added to function.str-ireplace
| From: | dave_st24 at hotmail dot com | Date: | Mon, 01 Dec 2008 16:23:45 +0000 |
| Subject: | note 87350 added to function.str-ireplace | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-147487@lists.php.net to get a copy of this message | ||
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>
?>
----
Server IP: 92.48.74.199
Probable Submitter: 81.143.53.73
----
Manual Page -- http://www.php.net/manual/en/function.str-ireplace.php
Edit -- https://master.php.net/note/edit/87350
Del: integrated -- https://master.php.net/note/delete/87350/integrated
Del: useless -- https://master.php.net/note/delete/87350/useless
Del: bad code -- https://master.php.net/note/delete/87350/bad+code
Del: spam -- https://master.php.net/note/delete/87350/spam
Del: non-english -- https://master.php.net/note/delete/87350/non-english
Del: in docs -- https://master.php.net/note/delete/87350/in+docs
Del: other reasons-- https://master.php.net/note/delete/87350
Reject -- https://master.php.net/note/reject/87350
Search -- https://master.php.net/manage/user-notes.php