note 76180 added to function.str-replace
| From: | Aaron at xavisys dot com | Date: | Tue, 03 Jul 2007 22:46:58 +0000 |
| Subject: | note 76180 added to function.str-replace | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-128212@lists.php.net to get a copy of this message | ||
In case anyone doesn't know, Erik's code will not work. Besides the major syntax flaws,
the count parameter returns how many replacements were made, it DOES NOT limit how many are made.
If you really need to replace every other occurrence, this DOES work:
<?php
function str_replace_every_other($needle, $replace, $haystack, &$count=null,
$replace_first=true) {
$count = 0;
$offset = strpos($haystack, $needle);
//If we don't replace the first, go ahead and skip it
if (!$replace_first) {
$offset += strlen($needle);
$offset = strpos($haystack, $needle, $offset);
}
while ($offset !== false) {
$haystack = substr_replace($haystack, $replace, $offset, strlen($needle));
$count++;
$offset += strlen($replace);
$offset = strpos($haystack, $needle, $offset);
if ($offset !== false) {
$offset += strlen($needle);
$offset = strpos($haystack, $needle, $offset);
}
}
return $haystack;
}
//Use it like this:
$str = "one two one two one two";
echo str_replace_every_other('one', 'two', $str, $count).'<br
/>';
//two two one two two two
echo str_replace_every_other('one', 'two', $str, $count, false).'<br
/>';
//one two two two one two
?>
I added the last option ($replace_first) to let you replace the odd occurrences (true, default) or
the evens (false).
----
Server IP: 69.147.83.197
Probable Submitter: 63.225.219.62
----
Manual Page -- http://www.php.net/manual/en/function.str-replace.php
Edit -- https://master.php.net/note/edit/76180
Del: integrated -- https://master.php.net/note/delete/76180/integrated
Del: useless -- https://master.php.net/note/delete/76180/useless
Del: bad code -- https://master.php.net/note/delete/76180/bad+code
Del: spam -- https://master.php.net/note/delete/76180/spam
Del: non-english -- https://master.php.net/note/delete/76180/non-english
Del: in docs -- https://master.php.net/note/delete/76180/in+docs
Del: other reasons-- https://master.php.net/note/delete/76180
Reject -- https://master.php.net/note/reject/76180
Search -- https://master.php.net/manage/user-notes.php