On 18 December 2012 13:24, Stefan Neufeind <neufe...@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"

Reply via email to