In PHP, preg_replace_callback() replaces each regex match by calling your function to build the replacement text.
The callback receives an array like preg_match() would put in $matches: [0] is the full match, [1] is group 1, and so on. Return the string that should replace that match.
Syntax
Call preg_replace_callback() with the values you need. Start with this line.
Can use a named function; returns "HI" for the letters.
preg_replace_callback('/\d+/', $fn, $text, 1)
Replaces only the first match when limit is 1.
Use a callback when the replacement depends on PHP logic (math, lookup tables, conditional text). For a fixed replacement string, preg_replace() is enough.
Library declarations
PHP
preg_replace_callback(string|array $pattern, callable $callback, string|array $subject, int $limit = -1, int &$count = null, int $flags = 0): string|array|null
Parameters
Parameter
Description
pattern
Required. PCRE pattern (or array of patterns) with delimiters.
callback
Required. Callable that receives the match array and returns the replacement string.
subject
Required. String or array of strings to process.
limit
Optional. Max replacements per subject. Default -1.
count
Optional. Receives how many replacements were made.
flags
Optional. For example PREG_OFFSET_CAPTURE. Default 0.
Return Value
Return Value
Description
string|array|null
The subject after callback replacements, or null on error.