Re: Extension for str_replace / preg_replace with arrays
| From: | Larry Garfield | Date: | Wed, 19 Dec 2012 23:18:36 +0000 |
| Subject: | Re: Extension for str_replace / preg_replace with arrays | ||
| References: | 1 2 3 4 | Groups: | php.internals |
| Request: | Send a blank email to internals+get-64369@lists.php.net to get a copy of this message | ||
On 12/18/12 7:44 AM, Leigh wrote:
On 18 December 2012 13:24, Stefan Neufeind <neufeind@php.net> wrote:You could likely simplify the code even further using an infinite iterator: http://us1.php.net/infiniteiterator $result = preg_replace_callback(Since we already have functionality for replacing with arrays in place, I wondered if giving it one string to replace and then an array to choose the replacement from (rotating) would be an option. Currently that's "unsupported" (either two strings or two arrays).It's certainly possible to implement, but personally it feels like odd behaviour. I don't know what other people think about it.I think you could use a callback-function but would need to add quite a few more lines to initialise your array first, do a "next()" on the array inside the callback-function and (how would you pass it that array?) and still would have to handle starting from beginning of the array again once you reach the end etc.You pass the array using "use". You could do it something like this: $replacements = array('one', 'two', 'three'); $result = preg_replace_callback('/word/', function($matches) use (&$replacements) { $current = current($replacements); next($replacements) || reset($replacements); return $current; }, 'word word word word word'); var_dump($result); Output: string(21) "one two three one two"
'/word/',
function($matches) use (&$replacements_iterator) {
return $replacements->next();
},
'word word word word word'
);
--Larry Garfield