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
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.
3 Comments
Vit Kos
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.??deceze
You'd use the closure aspect to do that:
..., function () use ($arr) { ... }, ....Vit Kos
thanks, that means I can use something like
...,function() use ($arr){ return array_shift($arr);},.... ?