Encodera

Thanks for reading!

Donate to the site — we work hard for you.

PHP reference

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|null

Parameters

ParameterTypeDescription
$patternstring|arrayThe regular expression.
$callbackcallableA function: receives the match array, returns the replacement.
$subjectstring|arrayThe input string.
$limitintOptional. 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 pears

From snake_case to camelCase:

<?php
 
echo preg_replace_callback('/_([a-z])/', fn ($m) => strtoupper($m[1]), 'user_first_name');

Output:

userFirstName

Notes

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.

Thanks for reading!

Donate to the site — we work hard for you.