ID: 11457 Comment by: jetweedy at hotmail dot com Reported By: adamw at uscho dot com Status: Assigned Bug Type: Feature/Change Request PHP Version: 4.0.5 Assigned To: pollita New Comment:
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; } Previous Comments: ------------------------------------------------------------------------ [2003-06-06 10:19:08] juwe at clasennet dot de Why not simply add a further optional argument? This way You could even distinguish if less values where replaced. Furthermore I'd like "limit" optionally to be an array, if "search" is of that type. This way You could specify different replace limitations for differrent strings to be replaced. Please correct me if I'm misled, but as far as I've seen in the sourcecode str_replace() is internally subdivided into two functions anyway, one "interface" and another function doing the "real work" for str_replace() and str_ireplace(). (BTW: Why not stri_replace()? Seems to be more apropriate..) By implementing this feature we could easily have the same for str_ireplace() as well without much work and therfor avoid lots of usage of regular expressions. ------------------------------------------------------------------------ [2003-05-31 09:21:10] [EMAIL PROTECTED] As of 5.0.0 the last parameter (count) is passed by reference (it is optional). So 2 choices : 1)passed not by reference - it's limit 2)passed by reference : the var is is_null() - all occurences are replaced the number is returned in "count", otoh if the var !is_null() -> use as limit. Comments? ------------------------------------------------------------------------ [2001-06-13 01:51:51] adamw at uscho dot com I've been racking my brain attempting to figure out a way to replace only the first instance of a specified string within a larger string. Obviously - str_replace does this ... but it does it for *all* instances. Other functions will *find* the first instance, but won't act upon it. I noticed, however, that "preg_replace" has a fourth parameter ... the "limit" parameter. How nice would this be for "str_replace" to have that 4th parameter?! It would avoid the need to use a regular expression function. I am open to workarounds and alternatives. Thank you for the consideration. ------------------------------------------------------------------------ -- Edit this bug report at http://bugs.php.net/?id=11457&edit=1