SyntaxStudy
Sign Up
PHP preg_replace() for String Replacement
PHP Intermediate 4 min read

preg_replace() for String Replacement

preg_replace()

preg_replace() replaces pattern matches with a replacement string. Use $1, $2 or ${1} to reference captured groups.

Example
<?php
// Remove all whitespace
$clean = preg_replace("/\s+/", " ", $text);

// Format phone number
$formatted = preg_replace("/^(\d{3})(\d{3})(\d{4})$/", "($1) $2-$3", "5551234567");
// "(555) 123-4567"

// Strip HTML tags (simplified)
$plain = preg_replace("/<[^>]+>/", "", $html);

// Replace multiple patterns at once
$result = preg_replace(
    ["/foo/", "/bar/"],
    ["baz", "qux"],
    "foo and bar"
);
// "baz and qux"
Pro Tip

Use $1 or ${1} (not \1) for backreferences in preg_replace() replacement strings.