Encodera

Thanks for reading!

Donate to the site — we work hard for you.

PHP reference

preg_replace

Replaces everything that matches a regular expression.

Syntax

preg_replace(string|array $pattern, string|array $replacement, string|array $subject): string|array|null

Parameters

ParameterTypeDescription
$patternstring|arrayA pattern or an array of patterns.
$replacementstring|arrayThe replacement. `$1`, `$2` insert the groups.
$subjectstring|arrayThe 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
15551234567

Rearranging parts with groups:

<?php
 
echo preg_replace('/(\d{4})-(\d{2})-(\d{2})/', '$3.$2.$1', '2025-01-30');

Output:

30.01.2025

Notes

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.

Thanks for reading!

Donate to the site — we work hard for you.