note 108239 deleted from function.str-replace by googleguy

From: Date: Tue, 22 Oct 2013 12:16:43 +0000
Subject: note 108239 deleted from function.str-replace by googleguy
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-197131@lists.php.net to get a copy of this message
Note Submitter: alice2287 at live dot com ---- I was surprisingly unable to find a function for performing replaces on strings that allowed for the specification of a limit on the number of occurrences of $search to replace. Here's a function that allows you to do so, and a second function that does the same while starting the replace from the last occurrence of $search: <?php function str_replace_limit($search,$replace,$subject,$limit,&$count = null) { $count = 0; if ($limit <= 0) return $subject; $occurrences = substr_count($subject,$search); if ($occurrences === 0) return $subject; else if ($occurrences <= $limit) return str_replace($search,$replace,$subject,$count); //Do limited replace $position = 0; //Iterate through occurrences until we get to the last occurrence of $search we're going to replace for ($i = 0; $i < $limit; $i++) $position = strpos($subject,$search,$position) + strlen($search); $substring = substr($subject,0,$position + 1); $substring = str_replace($search,$replace,$substring,$count); return substr_replace($subject,$substring,0,$position+1); } function str_replace_limit_reverse($search,$replace,$subject,$limit,&$count = null) { $count = 0; $search = strrev($search); $replace = strrev($replace); $subject = strrev($subject); return strrev(str_replace_limit($search,$replace,$subject,$limit,$count)); } ?>

« previous php.notes (#197131) next »