Re: Extension for str_replace / preg_replace with arrays
| From: | Leigh | Date: | Tue, 18 Dec 2012 13:44:40 +0000 |
| Subject: | Re: Extension for str_replace / preg_replace with arrays | ||
| References: | 1 2 3 | Groups: | php.internals |
| Request: | Send a blank email to internals+get-64341@lists.php.net to get a copy of this message | ||
On 18 December 2012 13:24, Stefan Neufeind <neufeind@php.net> wrote:
> 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"