PHP preg_replace_callback() Function
PHP Regular Expressions (PCRE)
The preg_replace_callback function performs a regular expression search and uses a callback for replacement.
Syntax
mixed preg_replace_callback ( mixed $pattern , callable $callback , mixed $subject [, int $limit = -1 [, int &$count ]] )
This function behaves identically to preg_replace() except that it allows you to specify a callback instead of replacement to compute the replacement string.
Parameter Description:
-
$pattern: the pattern to search for, which can be a string or an array of strings.
-
$callback: a callback function called each time a replacement is needed; it receives the results matched from subject as its arguments.
-
$subject: the target string or array of strings to be searched and replaced.
-
$limit: optional, the maximum number of replacements for each pattern on each subject string. Default is -1 (no limit).
-
$count: optional, the number of replacements performed.
Return Value
If subject is an array, preg_replace_callback() returns an array; otherwise it returns a string. NULL is returned on error.
If a match is found, returns the replaced target string (or array of strings); otherwise subject is returned unchanged.
Example
Example 1
The execution result is as follows:
April fools day is 04/01/2003
Last christmas was 12/24/2002