Vit Kos
Vit Kos

Reputation: 5755

preg_replace usage in php

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

Upvotes: 0

Views: 95

Answers (1)

deceze
deceze

Reputation: 522042

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.

Upvotes: 1

Related Questions