preg_replace_callback_array()

Using regular expressions to replace a matching substring with something else is quite a common task. However, simply replacing one static string by another is often not enough, so the need for a callback arises.

Given that PHP’s preg_replace_callback optionally accepts an array of patterns as its first argument, the defined callback would either have to treat all matches the same way or implement a rather complex decision logic to determine which pattern was matched for the current call.

To remove the need for such logic, a new function preg_replace_callback_array() was introduced. The behavior of this new function is similar to the preexisting preg_replace_callback(), except that callbacks are executed on a per-pattern basis. The first argument to preg_replace_callback_array() is an associative array where the key contains the patterns and the value the associated callback:

$result = preg_replace_callback_array(
    [
        '/(\w+)/' => function($match) {
                         return ucfirst($match[1]);
                     },
        '/(\d+)/' => function($match) {
                         return number_format($match[1], ',', '.');
                     }
    ],
    'This is an example string with a number 1234567 to match'
);

var_dump($result);

When executed, every word starts with an uppercase character, and the number is reformatted to contain a dot between every group of thousands:

string(58) "This Is An Example String With A Number 1.234.567 To Match"