preg_replace
Perform a regular expression search and replace.
preg_replace Function synopsis
preg_replace(
array|string $pattern,
array|string $replacement,
array|string $subject,
int $limit = -1,
&$count = null
): array|string|null
Parameters
$pattern
Typearray|string
The pattern to search for. It can be either a string or an array with strings.
$replacement
Typearray|string
The 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.
$subject
Typearray|string
The string or an array with strings to search and replace.
$limit
OptionalTypeintDefault value-1
The maximum possible replacements for each pattern in each
$subject string. Defaults to
-1 (no limit).
$count
Passed by reference, OptionalDefault valuenull
If specified, this variable will be filled with the number of replacements done.
Note that the parameter
$countis passed by reference, and contains additional/updated context data that may be useful.
Return value
Typearray|string|null
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.
Changes to the preg_replace Function
PHP 8.0
- Return type added:
array|string|null - Parameter name of parameter #1 changed:
$regexto$pattern - Parameter type added for parameter #1 (
$pattern):array|string - Parameter name of parameter #2 changed:
$replaceto$replacement - Parameter type added for parameter #2 (
$replacement):array|string - Parameter type added for parameter #3 (
$subject):array|string - Parameter type added for parameter #4 (
$limit):int - Parameter default value added for position #4 (
$limit):-1 - Parameter default value added for position #5 (
$count):null
preg_replace(
- $regex,
+ array|string $pattern,
- $replace,
+ array|string $replacement,
- $subject,
+ array|string $subject,
- $limit,
+ int $limit = -1,
- &$count
+ &$count = null
- )
+ ): array|string|null preg_replace Function Availability
preg_replace Function Availability| PHP Version | Availability |
|---|---|
| PHP 8.6Upcoming Release | Yes |
| PHP 8.5Supported (Latest) | Yes |
| PHP 8.4Supported | Yes |
| PHP 8.3Security-Fixes Only | Yes |
| PHP 8.2Security-Fixes Only | Yes |
| PHP 8.1Unsupported | Yes |
| PHP 8.0Unsupported | Yes |
| PHP 7.4Unsupported | Yes |
| PHP 7.3Unsupported | Yes |
| PHP 7.2Unsupported | Yes |
| PHP 7.1Unsupported | Yes |
| PHP 7.0Unsupported | Yes |
| PHP 5.6Unsupported | Yes |
| PHP 5.5Unsupported | Yes |
| PHP 5.4Unsupported | Yes |
| PHP 5.3Unsupported | Yes |