note 76180 deleted from function.str-replace by felipe
| From: | felipe@php.net | Date: | Sun, 06 Jan 2008 12:47:01 +0000 |
| Subject: | note 76180 deleted from function.str-replace by felipe | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-134869@lists.php.net to get a copy of this message | ||
Note Submitter: Aaron at xavisys dot com
----
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).