User Contributed Notes 3 notes

Based on some tests, I found these important traits of the function. (These wouldbe nice to see documented as part of its spec, e.g. for confirmation. Without that,this is just experimental curiosity. Still better than guesswork, though! ;) )

1. Changes cascade over a subject across callbacks, i.e. a change made to a subject by a callback will be seen by the next callback, if its pattern matches the changed subject. (But a change made by a previous call of the *same* callback (on any subject) will not be seen by that callback again.)

2. The pattern + callback pairs will be applied in the order of their appearance in $patterns_and_callbacks.

3. The callback can't be null (or '') for a quick shortcut for empty replacements.

4. Overall, the algorithm starts iterating over $patterns_and_callbacks, and then feeds each $subject to the current callback, repeatedly for every single match of its pattern on the current subject (unlike "preg_match_all", that is, which can do the same in one go, returning the accumulated results in an array).

This basically means that the "crown jewel", an even more efficient function: "preg_replace_all_callback_array" is still missing from the collection.

(Of course, that would better fit a new design of the regex API, where one API could flexibly handle various different modes via some $flags = [] array.)

5. (This last one is not specific to this function, but inherent to regexes, OTOH, it's probably more relevant here than anywhere else in PHP's regex support.)

Even apparently simple cases can generate a crazy (and difficult-to-predict) number of matches, and therefore callback invokations, so remember the set $limit, where affordable. But, of course, try to sharpen your patterns first!

E.g. use ^...$ anchoring to avoid unintended extra calls on matching substrings of a subject, (I.e. '/.*/', without anchoring, would match twice: once for the whole subject, and then for a trailing empty substring -- but I'm not quite sure this should actually be correct behavior, though.)