note 40056 added to function.str-replace
| From: | unusedacct at no$p at m dot comcast dot net | Date: | Fri, 20 Feb 2004 02:45:54 +0000 |
| Subject: | note 40056 added to function.str-replace | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-65436@lists.php.net to get a copy of this message | ||
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.
----
Manual Page -- http://www.php.net/manual/en/function.str-replace.php
Edit -- http://master.php.net/manage/user-notes.php?action=edit+40056
Delete -- http://master.php.net/manage/user-notes.php?action=delete+40056&report=yes
Reject -- http://master.php.net/manage/user-notes.php?action=reject+40056&report=yes
Search -- http://master.php.net/manage/user-notes.php