Regex Replacement, Validation and Security

8.Regex Replacement, Validation and Security

M

In this chapter

We'll learn how to clean and change text with preg_replace(), preg_replace_callback() and preg_split(), how to validate input safely — the $ newline trap, \z and filter_var() — and the security side of regex: preg_quote() for user input and catastrophic backtracking. The result is one function that turns every phone number into +447700900123, or rejects it.

16–18 min

The Problem in Real Life

Mia turns chapter 7's pattern into a check for the booking form: if preg_match('/^(\+44|0044|0)7\d{9}$/', $phone) fails, the form asks the customer to correct the number. She tries it on Tom's list. It accepts the good numbers and rejects the short one.

Then Marcus shows her one of the six numbers the SMS service rejected. On the screen it looks perfect: 07700900654. He prints it with var_dump(), which shows string(12). Eleven digits, twelve bytes. The twelfth byte is a new line, left behind when the customer pressed Enter. And her check says the number is valid.

M

Eleven digits and a new line. How can my pattern call that a valid number?

Mia

Looks Valid vs. Is Valid

$ isn't quite the end

In PHP's regex, $ also matches just before a final new line. A validator needs \z.

Clean, then check

Spaces, dashes and brackets aren't mistakes. Remove them first, then check what's left.

Patterns can be attacked

A badly written pattern can run almost forever on the wrong text, and user input inside a pattern can change its meaning.

Regex Replacement, Validation and Security

From matching to doing: chapter 7's functions answer "does it match?". This chapter adds the functions that change text, and the rules for using a pattern as a gatekeeper:

  • Replacing and splitting: preg_replace(), preg_replace_callback() and preg_split().
  • Validation: anchors that really mean "the whole text", and filter_var() for formats that are too hard for a hand-written regex.
  • Security: preg_quote(), catastrophic backtracking and preg_last_error_msg().

preg_replace: preg_replace($pattern, $replacement, $text) replaces every match of a pattern and returns the new string. Where str_replace() needs a list of every character to remove, a character class says it in one go: preg_replace('/[^\d+]/', '', $phone) removes everything that is not a digit or a plus sign — spaces, dashes, brackets, dots and new lines. In the replacement, $1, $2 and so on put back what a group captured, which lets you reshape text: '0$1 $2' turns +447700900123 back into the familiar 07700 900123.

preg_replace(): clean and reshape
<?php
$raw = " (07700) 900-123\n";
$digits = preg_replace('/[^\d+]/', '', $raw);
echo $digits, "\n"; // 07700900123
echo preg_replace('/^(?:\+44|0044|0)/', '+44', $digits), "\n"; // +447700900123
// $1 and $2 put back what the groups captured
echo preg_replace('/^\+44(\d{4})(\d{6})$/', '0$1 $2', "+447700900123"), "\n"; // 07700 900123

preg_replace_callback and preg_split: when each replacement needs a calculation, preg_replace_callback() calls a function for every match and puts in whatever that function returns. The function receives the $matches array, just like preg_match() fills it. You'll write functions like that properly in Act 09; here a short arrow function, fn($m) => ..., is enough. preg_split() is explode() with a pattern as the separator: preg_split('/[,;]\s*/', $services) splits at every comma or semicolon and swallows the spaces after it.

preg_replace_callback() and preg_split()
<?php
$note = "Haircut £25, beard trim £10";
// Add 10% to every price in the note
echo preg_replace_callback('/£(\d+)/', fn($m) => "£" . number_format($m[1] * 1.1, 2), $note), "\n";
// Haircut £27.50, beard trim £11.00
print_r(preg_split('/[,;]\s*/', "Haircut, Beard trim;Hot towel"));
// Array
// (
// [0] => Haircut
// [1] => Beard trim
// [2] => Hot towel
// )

The $ trap and \z: here's the hole Marcus didn't mention. In PHP's regex, $ means "the end of the text, or just before a new line at the very end". So /^...7\d{9}$/ happily matches a number followed by \n. For searching that's convenient; for validation it's a bug, because the new line gets through the check and is saved with the number. Use \z instead, which means "the very end, nothing after it", or add the D flag, which makes $ strict. A validation pattern should always say "from the very start to the very end": ^...\z.

The $ trap: a new line slips through
<?php
$phone = "07700900654\n"; // the customer pressed Enter
var_dump(preg_match('/^(\+44|0044|0)7\d{9}$/', $phone)); // int(1): $ allows a final new line
var_dump(preg_match('/^(\+44|0044|0)7\d{9}\z/', $phone)); // int(0): \z is the very end
var_dump(preg_match('/^(\+44|0044|0)7\d{9}$/D', $phone)); // int(0): the D flag makes $ strict

Clean, then check, then store one format: the full recipe for a phone number has three steps, shown in the diagram below. First, remove everything that isn't a digit or a plus sign. Second, check what's left with one anchored pattern that also captures the ten digits. Third, build the stored number from the capture: +44 and the ten digits. That format — a plus, the country code and the number, with no spaces — is called E.164, and SMS services and phone systems expect it. Store each number once, cleaned, and every later comparison is a simple === (chapter 5).

normalizePhone(): clean, check, store one format

" (07700) 900-123\n"

what the customer typed

1. clean

preg_replace('/[^\d+]/', '', $raw)

remove everything except digits and +: "07700900123"

2. check

/^(?:\+44|0044|0)(7\d{9})\z/

one anchored pattern; group 1 is "7700900123"

3. store

"+44" . $matches[1]

"+447700900123", or null if the check failed

normalizePhone(): every format in, one format out
<?php
function normalizePhone(string $raw): ?string
{
$digits = preg_replace('/[^\d+]/', '', $raw); // 1. clean
if (!preg_match('/^(?:\+44|0044|0)(7\d{9})\z/', $digits, $matches)) { // 2. check
return null;
}
return "+44" . $matches[1]; // 3. one format
}
$typed = [
"07700 900123", "+44 7700 900123", "(07700) 900-123", "0044 7700 900 123",
"07700-900-123", "07700900654\n", "0770 090 012", "call me",
];
foreach ($typed as $raw) {
$shown = str_replace("\n", '\n', $raw); // show the new line as \n
echo str_pad($shown, 20), normalizePhone($raw) ?? "rejected", "\n";
}
// 07700 900123 +447700900123
// +44 7700 900123 +447700900123
// (07700) 900-123 +447700900123
// 0044 7700 900 123 +447700900123
// 07700-900-123 +447700900123
// 07700900654\n +447700900654
// 0770 090 012 rejected
// call me rejected

Don't write every validator yourself: some formats are much harder than they look; a fully correct email regex is thousands of characters long. PHP's filter_var() has tested validators built in. filter_var($email, FILTER_VALIDATE_EMAIL) returns the email address, or false if it isn't valid, and there are filters for URLs, IP addresses, whole numbers and decimal numbers. For a whole number in a range, use FILTER_VALIDATE_INT with the options min_range and max_range. Use a regex for your own formats, like a UK mobile number or a booking code, and filter_var() for the standard ones.

filter_var() for standard formats
<?php
var_dump(filter_var("clare@example.com", FILTER_VALIDATE_EMAIL)); // string(17) "clare@example.com"
var_dump(filter_var("clare@", FILTER_VALIDATE_EMAIL)); // bool(false)
$chairs = ["options" => ["min_range" => 1, "max_range" => 3]];
var_dump(filter_var("2", FILTER_VALIDATE_INT, $chairs)); // int(2)
var_dump(filter_var("9", FILTER_VALIDATE_INT, $chairs)); // bool(false): Tom has 3 chairs

Security, catastrophic backtracking: when a regex engine tries one way to match and it fails, it goes back and tries another; that's called backtracking. A pattern with a repeat inside a repeat, like /^(a+)+$/, has an enormous number of ways to try on text that almost matches: thirty a's and a b can take billions of steps. PHP stops after a limit, set by pcre.backtrack_limit, and preg_match() returns false — not 0. If you only write if (!preg_match(...)), that false looks like "no match" and nobody notices. Someone who knows your pattern can send such text on purpose to slow your server down. That attack is called ReDoS, regular expression denial of service. So: no repeats inside repeats, keep validation patterns short and anchored, and check for false with preg_last_error_msg().

Catastrophic backtracking: false, not 0
<?php
$text = str_repeat("a", 30) . "b";
var_dump(preg_match('/^(a+)+$/', $text)); // bool(false): PHP gave up
echo preg_last_error_msg(), "\n"; // Backtrack limit exhausted
var_dump(preg_match('/^a+$/', $text)); // int(0): the same check without the repeat inside a repeat, instantly

Security, user input inside a pattern: if you build a pattern from something a user typed, their dots, plus signs and brackets become regex syntax. A search for "+44 (0)" breaks the pattern, and cleverer input can make it do far more work than you planned. preg_quote($text, '/') puts a backslash in front of every special character, so the text is matched exactly as typed. Better still, if you only need to find plain text, use str_contains() and skip regex altogether. The table below sums up the rules.

Table — Regex security rules
RiskWhat happensWhat to do
$ before a final new line"07700900123\n" passes a ^...$ checkAnchor validators with ^...\z, or add the D flag
Catastrophic backtracking (ReDoS)A pattern like (a+)+ runs for ages, then preg_match() returns falseNo repeats inside repeats; check for false
User input in a patternIts . + ( ) become regex syntaxpreg_quote($text, '/'), or use str_contains()
A hand-written email regexRejects real addresses, accepts broken onesfilter_var($email, FILTER_VALIDATE_EMAIL)
Checking without cleaning" 07700 900123 " is stored as typedClean, validate, then store one format
User input in a pattern: preg_quote()
<?php
$search = "+44 (0)"; // typed by a user
$text = "Call +44 (0) 7700 900123";
var_dump(preg_match('/' . $search . '/', $text));
// Warning: preg_match(): Compilation failed: quantifier does not follow a repeatable item at offset 0
// bool(false)
var_dump(preg_match('/' . preg_quote($search, '/') . '/', $text)); // int(1)
var_dump(str_contains($text, $search)); // bool(true): no regex needed at all

Key Takeaway

preg_replace() replaces every match ($1 puts a captured group back), preg_replace_callback() works out each replacement, and preg_split() splits at a pattern. To validate, clean the input first, then check it with a pattern anchored from ^ to \z — $ also matches before a final new line. Use filter_var() for standard formats like email, preg_quote() for user text inside a pattern, and avoid repeats inside repeats, which can make a regex run almost forever.

Why This Matters

Every piece of text a customer sends is input you have to check before you store it. Cleaning it, checking it from the very start to the very end, and storing one format means the SMS service, the lookup and the reminders all see the same +447700900123.

And a regex is code that runs on someone else's text. One new line at the end, one repeat inside a repeat or one unescaped plus sign is enough to let bad data in or slow the server down. These rules come back with Laravel's validation in the next course.

normalizePhone() turns all five formats into +447700900123, rejects the rest, and a new line can't slip through any more. Olivia runs it over every stored customer: five of the six numbers the SMS service rejected are now valid, and the sixth really is two digits short, so Tom calls that customer. One job is left: the reminder script still uses the old code. That's the checkpoint.