preg_replace()

preg_replace() — Perform a regular expression search and replace.

Built-in function of PHP 8.5. The manual lists it as available in PHP 4, 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

Searches subject for matches to pattern and replaces them with replacement.

Signature

preg_replace(string|array $pattern, string|array $replacement, string|array $subject, int $limit = -1, int &$count = null): string|array|null

Parameters

ParameterTypeWhat it takes
$patternstring|arrayThe pattern to search for. It can be either a string or an array with strings.
$replacementstring|arrayThe string or an array with strings to replace. If this parameter is a string and the pattern parameter is an array, all patterns will be replaced by that string. If both pattern and replacement parameters are arrays, each pattern will be replaced by the replacement counterpart. If there are fewer elements in the replacement array than in the pattern array, any extra patterns will be replaced by an empty string.
$subjectstring|arrayThe string or an array with strings to search and replace.
$limitintThe maximum possible replacements for each pattern in each subject string. Defaults to -1 (no limit).
&$countintIf specified, this variable will be filled with the number of replacements done.

Return value

preg_replace() returns an array if the subject parameter is an array, or a string otherwise. If matches are found, the new subject will be returned, otherwise subject will be returned unchanged or null if an error occurred.

Example

A runnable snippet:

$string = 'April 15, 2003'; $pattern = '/(\w+) (\d+), (\d+)/i'; $replacement = '${1}1,$3'; echo preg_replace($pattern, $replacement, $string);

Output:

April1,2003

See also

preg_quote(), preg_filter(), preg_match(), preg_replace_callback(), preg_split(), preg_last_error(), str_replace()

All PHP 8.5 built-in functions

Reference card built from the PHP manual page preg_replace() (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.