PHP preg_replace() Function

Search and replace using a regular expression

Try preg_replace() - edit and run
Output
Call XXX-XXX-4567 or XXX-XXX-6543
too many spaces

What does preg_replace() do?

preg_replace() finds every match of a regular expression in $subject and replaces it. In the replacement, $1, $2 ... (or ${1}) refer to capture groups, and $0 is the whole match.

Syntax

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

Parameters

  • $pattern - Regex with delimiters, or an array of patterns.
  • $replacement - Replacement string (may contain $n back-references) or an array matching the patterns.
  • $subject - The string or array of strings to process.
  • $limit - Maximum replacements per pattern and subject; -1 means no limit.
  • $count - Optional variable that receives the number of replacements.

Return value

The new string (or array). Returns null if an error occurred; check preg_last_error_msg().

preg_replace() examples

Every example below shows the exact output it produces. Paste any of them into the editor above (or the online compiler) to run it.

1. Mask phone numbers and collapse whitespace

<?php
$text = "Call 555-123-4567 or 555-987-6543";
echo preg_replace('/\d{3}-\d{3}-(\d{4})/', 'XXX-XXX-$1', $text) . "\n";
echo preg_replace('/\s+/', ' ', "too    many   spaces") . "\n";

Output:

Call XXX-XXX-4567 or XXX-XXX-6543
too many spaces

2. Reorder with back-references and replace whole words

<?php
echo preg_replace('/(\d{4})-(\d{2})-(\d{2})/', '$3/$2/$1', "Due: 2026-03-15") . "\n";
echo preg_replace('/\bcat\b/i', 'dog', "Cat, cats and a cat.") . "\n";

Output:

Due: 15/03/2026
dog, cats and a dog.

3. Create a URL slug

<?php
function slugify(string $title): string {
    $slug = strtolower(trim($title));
    $slug = preg_replace('/[^a-z0-9]+/', '-', $slug);
    return trim($slug, '-');
}
echo slugify("  Hello World! PHP 8.3 Tips ") . "\n";

Output:

hello-world-php-8-3-tips

4. Callbacks, limit and count

<?php
$text = "apples: 3, pears: 5";
echo preg_replace_callback('/\d+/', fn($m) => $m[0] * 2, $text) . "\n";

$result = preg_replace('/a/', 'A', "banana", 2, $count);
echo "$result ($count replacements)\n";

Output:

apples: 6, pears: 10
bAnAna (2 replacements)

Common mistakes and gotchas

  • Literal text? If you are not using any regex features, str_replace() is simpler and faster.
  • Back-reference followed by a digit: write ${1}0 instead of $10, which PHP reads as group 10.
  • null on error: an invalid pattern or a catastrophic-backtracking limit returns null; check before using the result.
  • UTF-8 text: add the u modifier so multibyte characters are treated as single characters.

PHP preg_replace() FAQ

What is the difference between preg_replace() and str_replace()?

str_replace() replaces fixed text; preg_replace() replaces regex matches and supports word boundaries, character classes and back-references.

How do I use the matched text in the replacement?

Use $0 for the whole match and $1, $2 ... for capture groups. For computed replacements use preg_replace_callback().

How do I replace only the first match?

Pass a limit of 1: preg_replace($pattern, $replacement, $subject, 1).