English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
The preg_replace_callback_array() function performs a regular expression search and uses a callback for replacement.
This function is supported in PHP7+ Version Support.
mixed preg_replace_callback_array ( array $patterns_and_callbacks , mixed $subject [, int $limit =) -1 [, int &$count ]] )
Function Similar to preg_replace_callback(), but it is based on each pattern match to call the callback function for replacement.
Parameter Description:
$patterns_and_callbacks: Associative array, key(pattern) => value(callback function)
$subject: The string or array to be searched and replaced.
$limit: Optional, the maximum number of replacements for each pattern, default is -1(Unlimited, replace all matches).
$count: Optional, specify the number of replacements.
If subject is an array, return an array; otherwise, return a string. Return NULL if an error occurs.
If a match is found, return the replaced target string (or string array), otherwise subject will be returned unchanged.
<?php
$subject = 'Aaaaaa Bbb';
preg_replace_callback_array(
[
'~[a]+~i' => function ($match) {
echo strlen($match[0]), ' matches for "a" found', PHP_EOL;
},
'~[b]+~i' => function ($match) {
echo strlen($match[0]), ' matches for "b" found', PHP_EOL;
}
],
$subject
);
?>
The execution result is as follows:
6 matches for "a" found 3 matches for "b" found