Edit report at http://bugs.php.net/bug.php?id=11457&edit=1
ID: 11457
Comment by: cancausecancerr at yahoo dot com dot cn
Reported by: adamw at uscho dot com
Summary: limit for str_replace()
Status: Wont fix
Type: Feature/Change Request
Package: *General Issues
PHP Version: 4.0.5
Block user comment: N
Private report: N
New Comment:
I would vote to add a str_replaceonce function where the $count arg
specifies which occurrence in the string to change (negatives also.)
Changing the existing str_replace is something people can do on their
own installation but I don't think it will be changed in the main code
because it could break some existing software written in php.
Previous Comments:
------------------------------------------------------------------------
[2011-01-17 02:59:37] TrentTompkins at gmail dot com
This is such a great idea! I can't believe it was suggested 10 years ago
and no one added it =/
------------------------------------------------------------------------
[2010-12-01 16:24:23] jani@php.net
Use preg_replace() if you need this.
------------------------------------------------------------------------
[2009-11-18 16:44:37] felipe dot tonello at felipetonello dot com
On version 5.3.0 the 4th parameter, count, does not work when not passed
by reference.
$count = 1;
echo str_replace("o", "a", "foo", $count); // returns "faa"
Even if it was working well, thought, this is not a good approach.
------------------------------------------------------------------------
[2009-04-19 01:46:26] phpnet at sabintr dot com
How about this...
$count is passed by reference. Don't change this.
if (is_null($count)) {
//replace all;
} elseif (floor($count) < 1) {
//replace all;
} else {
//replace first floor($count) occurences;
}
$count = number of actual replacements made
The only change from past behavior is that $count must be unset or made
NULL before passing it by reference:
echo str_replace("o", "a", "moo", $count); // returns "maa"
echo str_replace("o", "a", "mooooo", $count); // returns
"maaooo"
unset($count);
echo str_replace("o", "a", "mooooo", $count); // returns
"maaaaa"
Thoughts?
------------------------------------------------------------------------
[2007-10-17 14:39:22] jetweedy at hotmail dot com
In response to this, here's a simple function to replace the first one
only (note that you could loop this function to replace more than one,
but not all):
function str_replaceFirst($s,$r,$str)
{
$l = strlen($str);
$a = strpos($str,$s);
$b = $a + strlen($s);
$temp = substr($str,0,$a) . $r . substr($str,$b,($l-$b));
return $temp;
}
------------------------------------------------------------------------
The remainder of the comments for this report are too long. To view
the rest of the comments, please view the bug report online at
http://bugs.php.net/bug.php?id=11457--
Edit this bug report at http://bugs.php.net/bug.php?id=11457&edit=1