The preg_replace_callback_array Function
The preg_replace_callback_array function allows performing multiple replacements in a string using different callback functions for each regular expression. The first parameter of the function accepts an associative array where keys are regular expressions and values are callback functions. The second parameter is the string to be processed.
Syntax
preg_replace_callback_array(array $patterns_and_callbacks, string $subject): string
Example
Let's replace numbers with their squares and letters with uppercase:
<?php
$str = 'a1b2c3';
$res = preg_replace_callback_array([
'/\d+/' => function($matches) {
return $matches[0] * $matches[0];
},
'/[a-z]/' => function($matches) {
return strtoupper($matches[0]);
}
], $str);
echo $res;
?>
Code execution result:
'A1B4C9'
Example
Let's convert dates from one format to another and highlight numbers in bold:
<?php
$text = 'Date: 2023-05-15';
$res = preg_replace_callback_array([
'/(\d{4})-(\d{2})-(\d{2})/' => function($matches) {
return $matches[3].'.'.$matches[2].'.'.$matches[1];
},
'/\d+/' => function($matches) {
return '<b>'.$matches[0].'</b>';
}
], $text);
echo $res;
?>
Code execution result:
'Date: <b>15</b>.<b>05</b>.<b>2023</b>'
See Also
-
the
preg_replace_callbackfunction,
which performs replacement with a single callback function -
the
preg_replacefunction,
which performs replacement using a regular expression