PHP preg_replace_callback_array() Function
PHP Regular Expressions (PCRE)
The preg_replace_callback_array function performs a regular expression search and uses a callback for replacement.
This function is supported in PHP 7+.
Syntax
mixed preg_replace_callback_array ( array $patterns_and_callbacks , mixed $subject [, int $limit = -1 [, int &$count ]] )
The function is similar to preg_replace_callback(), but it invokes the callback based on each pattern match for replacement.
Parameter Description:
-
$patterns_and_callbacks: an associative array, key (pattern) => value (callback function)
-
$subject: the string or array to search and replace.
-
$limit: optional, the maximum number of replacements per pattern, default -1 (no limit, match all).
-
$count: optional, specifies the number of replacements.
Return Value
If subject is an array, returns an array; otherwise returns a string. Returns NULL on error.
If a match is found, returns the replaced target string (or array of strings); otherwise subject is returned unchanged.
Example
Example 1
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