# `preg_replace_callback_array()`

> Section in “New and Extended Functionality › Regular Expressions” of the book [PHP 7 Explained](https://php7explained.com/) by Sebastian Bergmann and Stefan Priebsch, published by thePHP.cc. The book covers PHP 7.0 to 7.4 and was last updated in November 2020. HTML version: <https://php7explained.com/new-and-extended-functionality/regular-expressions/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:

``` php
$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"

---

Previous: [preg_quote() and the # Character](https://php7explained.com/new-and-extended-functionality/regular-expressions/preg_quote-and-the-character/index.html.md) | Next: [Flags for preg_replace_callback() and preg_replace_callback_array()](https://php7explained.com/new-and-extended-functionality/regular-expressions/flags-for-preg_replace_callback-and-preg_replace_callback_array/index.html.md)
