note 108239 added to function.str-replace
| From: | alice2287atlivedotcom | Date: | Tue, 10 Apr 2012 20:50:59 +0000 |
| Subject: | note 108239 added to function.str-replace | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-187049@lists.php.net to get a copy of this message | ||
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));
}
?>
----
Server IP: 72.55.140.6
Probable Submitter: 208.97.108.26
----
Manual Page -- http://www.php.net/manual/en/function.str-replace.php
Edit -- https://master.php.net/note/edit/108239
Del: integrated -- https://master.php.net/note/delete/108239/integrated
Del: useless -- https://master.php.net/note/delete/108239/useless
Del: bad code -- https://master.php.net/note/delete/108239/bad+code
Del: spam -- https://master.php.net/note/delete/108239/spam
Del: non-english -- https://master.php.net/note/delete/108239/non-english
Del: in docs -- https://master.php.net/note/delete/108239/in+docs
Del: other reasons-- https://master.php.net/note/delete/108239
Reject -- https://master.php.net/note/reject/108239
Search -- https://master.php.net/manage/user-notes.php