note 40056 deleted from function.str-replace by felipe
| From: | felipe@php.net | Date: | Sun, 06 Jan 2008 12:49:35 +0000 |
| Subject: | note 40056 deleted from function.str-replace by felipe | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-134884@lists.php.net to get a copy of this message | ||
Note Submitter: unusedacct at no$p at m dot comcast dot net
----
For those who haven't yet updated to PHP 5 yet, here is a quick function to do regular
str_replace on a string [not arrays] only a certain number of times:
<?php
function str_replace_count($find,$replace,$subject,$count)
{
$subjectnew = $subject;
$pos = strpos($subject,$find);
if ($pos !== FALSE)
{
while ($pos !== FALSE)
{
$nC = $nC + 1;
$temp = substr($subjectnew,$pos+strlen($find));
$subjectnew = substr($subjectnew,0,$pos) . $replace . $temp;
if ($nC >= $count)
{
break;
}
$pos = strpos($subjectnew,$find);
} // closes the while loop
} // closes the if
return $subjectnew;
}
$stuff = "a b a b a b a b a";
print $stuff . " -- the old string<br>\n";
print str_replace_count("a ","c ",$stuff,4) . " -- the new
string<br>\n";
// will output c b c b c b c b a -- the new string
?>
Hope this helps.