preg_replace
Replaces everything that matches a regular expression.
Syntax
preg_replace(string|array $pattern, string|array $replacement, string|array $subject): string|array|nullParameters
| Parameter | Type | Description |
|---|---|---|
| $pattern | string|array | A pattern or an array of patterns. |
| $replacement | string|array | The replacement. `$1`, `$2` insert the groups. |
| $subject | string|array | The source string. |
Return value
string|array|nullThe string with the replacements.
Examples
Extra spaces, and digits only:
<?php
echo preg_replace('/\s+/', ' ', 'too many spaces'), "\n";
echo preg_replace('/\D/', '', '+1 (555) 123-45-67');Output:
too many spaces
15551234567Rearranging parts with groups:
<?php
echo preg_replace('/(\d{4})-(\d{2})-(\d{2})/', '$3.$2.$1', '2025-01-30');Output:
30.01.2025Notes
For a plain replacement without a pattern use str_replace() — it is faster and clearer.
See also
- preg_match — Tests a string against a regular expression.
- str_replace — Replaces all occurrences of a substring with another string.
Related recipes
In the tutorial
- Regular expressions — Regular expressions in PHP — preg_match, preg_replace, preg_split, groups and the basic pattern notation.