0

can someone tell me if there is posibility to use one pattern for multiple replacement?I have a pattern, and a replacement array and I seek to replace the matches sequentially from the array. Like match = > array[0] match = > array[1] and so on. Thanks

1 Answer 1

1

I'd go with a preg_replace with callback:

preg_replace_callback('/pattern/', function () {
    static $replacements = array('foo', 'bar', 'baz');
    return array_shift($replacements);
}, $subject);

Each subsequent match will get the next entry from the replacement array.

Sign up to request clarification or add additional context in comments.

3 Comments

one more moment, how not to make static array in the callback function but pass it via parameter? when I pass my array like preg_replace_callback($pattern,function($arr){ .... },$subject); I get the same values as were before.??
You'd use the closure aspect to do that: ..., function () use ($arr) { ... }, ....
thanks, that means I can use something like ...,function() use ($arr){ return array_shift($arr);},.... ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.