CodeBlanks Logo Icon CodeBlanks

Replacing with preg_replace()

PHP course · Advanced · Lesson 42/92

Learn to replace matched patterns with a new value using preg_replace().

Replacing with preg_replace

preg_replace($pattern, $replacement, $subject) replaces every matched piece with a new string. It takes three parameters: the pattern, the replacement text, and the source text.

For example, preg_replace("/\d/", "X", "Tel: 0555") turns each digit into X and returns "Tel: XXXX". If nothing matches, the text is returned unchanged.

The return value is the new text; the original variable is not changed. You assign it to a variable or print it directly.

Modifiers: i and u

A modifier is added as a letter after the closing delimiter. The two most common ones are:

i: case-insensitive matching. The pattern /apple/i matches both apple and APPLE.

u: UTF-8 mode. Required so that shortcuts like \w and \s work correctly on text with non-ASCII letters such as ç, ğ.

Modifiers can be combined: /apple/iu turns both features on.

Exercise Replace digits with X

Replace every digit in $phone = "Tel: 0555 123 45 67"; with X using preg_replace. Put the pattern into $pattern, the replacement into $replacement, the result into $result, and print $result on a new line.

Show example solution
Set pattern to "/\d/". Replacement is "X". Assign with $result = preg_replace($pattern, $replacement, $phone); then echo $result . "\n";
Example solution:
<?php
// Replace digits with X using preg_replace

$phone = "Tel: 0555 123 45 67";
// Add pattern, replacement and the call
$pattern = "/\d/";
$replacement = "X";
$result = preg_replace($pattern, $replacement, $phone);

// Print the result
echo $result . "\n";

Test yourself

  1. Assign the pattern to a variable

    $pattern = ____;
    $result = preg_replace($pattern, "X", "Tel: 0555");
    echo $result . "\n";
    Show answer
    $pattern = "/\d/";
    $result = preg_replace($pattern, "X", "Tel: 0555");
    echo $result . "\n";
  2. Which modifier enables case-insensitive matching?

    • u
    • m
    • i
    • s
    Show answer

    i — Correct. i (case-insensitive) ignores letter case.

  3. Understand the modifiers

    i
    Case-insensitive
    u
    UTF-8 mode
    m
    Multiline mode
    s
    Dot matches newlines

All lessons in Advanced