preg_replace_callback
Replaces pattern matches with the result of a function.
Syntax
preg_replace_callback(string|array $pattern, callable $callback, string|array $subject, int $limit = -1): string|array|nullParameters
| Parameter | Type | Description |
|---|---|---|
| $pattern | string|array | The regular expression. |
| $callback | callable | A function: receives the match array, returns the replacement. |
| $subject | string|array | The input string. |
| $limit | int | Optional. The maximum number of replacements. |
Return value
string|array|nullThe string after the replacements.
Examples
Doubling every number in a text:
<?php
echo preg_replace_callback('/\d+/', fn ($match) => $match[0] * 2, '3 apples and 12 pears');Output:
6 apples and 24 pearsFrom snake_case to camelCase:
<?php
echo preg_replace_callback('/_([a-z])/', fn ($m) => strtoupper($m[1]), 'user_first_name');Output:
userFirstNameNotes
The function is needed when the replacement depends on the matched text. For plain substitution preg_replace() is enough.
See also
- preg_replace — Replaces everything that matches a regular expression.
- preg_match_all — Finds every match of a regular expression.
- array_map — Applies a function to every element of an array.
Related recipes
In the tutorial
- Regular expressions — Regular expressions in PHP — preg_match, preg_replace, preg_split, groups and the basic pattern notation.