|
php.net | support | documentation | report a bug | advanced search | search howto | statistics | random bug | login |
[2001-06-13 01:51 UTC] 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. PatchesPull RequestsHistoryAllCommentsChangesGit/SVN commits
|
|||||||||||||||||||||||||||||||||||||
Copyright © 2001-2025 The PHP GroupAll rights reserved. |
Last updated: Tue Oct 28 02:00:01 2025 UTC |
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; }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?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.Are you kidding me? 13 years and "Won't fix"? Simple code: $bb_code = array('[b]','[/b]','[i]','[/i]','[u]','[/u]'); $html_code = array('<b>','</b>','<i>','</i>','<u>','</u>'); $html = str_replace($bb_code,$html_code,$edit); Task: Allow to use bbcode only 2 times in whole article. Good luck with preg_replace. I know it's possible, but when it comes to performance... yeah, right. I'm too 'oldschool' to use "plugins" and "libraries" to replace BBCode, and much too old to waste my servertime for preg_replace. After years of crappy programming and wasting resources it's time to start doing it right - as it was years ago. So for God sake just add this simple limit, as you count replaces anyway...