preg_replace_callback()
preg_replace_callback() — Perform a regular expression search and replace using a callback.
Built-in function of PHP 8.5. The manual lists it as available in PHP 4 >= 4.0.5, PHP 5, PHP 7, PHP 8. This page is the reference card: signature, parameters and return value, plus the changelog and the example the manual provides.
What it does
The behavior of this function is almost identical to preg_replace(), except for the fact that instead of replacement parameter, one should specify a callback.
Signature
preg_replace_callback(string|array $pattern, callable $callback, string|array $subject, int $limit = -1, int &$count = null, int $flags = 0): string|array|null handler(array $matches): string
Parameters
| Parameter | Type | What it takes |
|---|---|---|
| $pattern | string|array | The pattern to search for. It can be either a string or an array with strings. |
| $callback | callable | A callback that will be called and passed an array of matched elements in the subject string. The callback should return the replacement string. This is the callback signature: |
| $subject | string|array | The string or an array with strings to search and replace. |
| $limit | int | The maximum possible replacements for each pattern in each subject string. Defaults to -1 (no limit). |
| &$count | int | If specified, this variable will be filled with the number of replacements done. |
| $flags | int | flags can be a combination of the PREG_OFFSET_CAPTURE and PREG_UNMATCHED_AS_NULL flags, which influence the format of the matches array. See the description in preg_match() for more details. |
Return value
preg_replace_callback() returns an array if the subject parameter is an array, or a string otherwise. On errors the return value is null If matches are found, the new subject will be returned, otherwise subject will be returned unchanged.
Example
A runnable snippet:
// this text was used in 2002 // we want to get this up to date for 2003 $text = "April fools day is 04/01/2002\n"; $text.= "Last christmas was 12/24/2001\n"; // the callback function function next_year($matches) { // as usual: $matches[0] is the complete match // $matches[1] the match for the first subpattern // enclosed in '(...)' and so on return $matches[1].($matches[2]+1); } echo preg_replace_callback( "|(\d{2}/\d{2}/)(\d{4})|", "next_year", $text);
Output:
April fools day is 04/01/2003 Last christmas was 12/24/2002
Changelog
| Version | Change |
|---|---|
| 7.4.0 | The flags parameter was added. |
See also
preg_replace_callback_array(), preg_quote(), preg_replace(), preg_last_error()
All PHP 8.5 built-in functions
Reference card built from the PHP manual page preg_replace_callback() (PHP documentation, CC BY 3.0). The page is generated from the manual, so the wording of the parameter and return value text follows php.net.