PHP
Replacing with preg_replace()
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
-
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";
-
Which modifier enables case-insensitive matching?
Show answer
i — Correct. i (case-insensitive) ignores letter case.
-
Understand the modifiers
- i
- Case-insensitive
- u
- UTF-8 mode
- m
- Multiline mode
- s
- Dot matches newlines
Next lesson: All matches with preg_match_all()