Regular Expressions with PCRE

7.Regular Expressions with PCRE

M

In this chapter

We'll learn what regular expressions are and how PHP's PCRE functions use them: delimiters, character classes, quantifiers and anchors, preg_match() and preg_match_all(), capturing groups to pull parts out of a match, and lookarounds to check what comes before or after — all to recognise a UK mobile number in any of five formats.

17–19 min

The Problem in Real Life

The second problem. The SMS service's report says 6 of the 20 reminders were rejected: "invalid number". Mia lists every phone number Tom's customers typed. The same kind of number appears in five shapes: "07700 900123", "+44 7700 900123", "(07700) 900-123", "0044 7700 900 123" and "07700-900-123". One isn't a valid number at all: "0770 090 012" is two digits short.

Her first plan is str_replace() for the spaces, then the dashes, then the brackets, and a str_starts_with() for each way of writing the country code. After ten lines she has an if for every shape, and still no way to say what a valid number is.

"You're describing the shape of a phone number," says Marcus. "There's a small language made just for that."

M

Five formats, and an if for each one. Can't I just describe what a phone number looks like?

Mia

An if for Every Format vs. One Pattern

One rule per format

str_replace() and str_starts_with() need another line for every way people write a number.

Describe the shape

"A 0, then a 7, then nine more digits" is a pattern. Regular expressions are a language for patterns.

Take it apart

A match can also capture parts — like the digits after the country code — so you can rebuild the number.

Regular Expressions with PCRE

What a regular expression is: a regular expression, or regex, is a pattern that describes the shape of some text: "one or more digits", "starts with +44", "a 0, a 7, then nine digits". PHP uses a library called PCRE (Perl Compatible Regular Expressions), and its functions all start with preg_. This chapter builds the pattern for a UK mobile number piece by piece:

  • The pattern language: delimiters, normal characters, character classes, quantifiers, anchors and alternatives.
  • preg_match() and preg_match_all(): does the text match, and what matched?
  • Capturing groups: pulling parts out of a match, by number or by name.
  • Lookarounds: checking what comes before or after, without making it part of the match.

Delimiters and preg_match: in PHP, a pattern is a string with a delimiter at both ends, usually a slash: '/07700/'. After the closing delimiter come optional flags, like i for "ignore case": '/vip/i'. Write patterns in single quotes, so PHP doesn't treat backslashes and $ as escapes or variables. preg_match($pattern, $text) returns 1 if the pattern is found anywhere in the text, 0 if it isn't, and false if something went wrong, like a broken pattern.

preg_match() and the i flag
<?php
$note = "VIP - call 07700 900123 after 5";
var_dump(preg_match('/07700/', $note)); // int(1): found
var_dump(preg_match('/vip/', $note)); // int(0): case matters
var_dump(preg_match('/vip/i', $note)); // int(1): the i flag ignores case

Characters, classes and quantifiers: most characters in a pattern match themselves: /07700/ finds exactly 07700. A few have a special meaning: . * + ? ^ $ ( ) [ ] { } |, the backslash and the delimiter. To match one of them as a normal character, put a backslash in front: \+ matches a plus sign. A character class in square brackets matches one character from a list: [0-9] is any digit, [ -] a space or a dash, and [^0-9] anything that is not a digit. There are shortcuts: \d is a digit, \s a space, tab or new line, \w a letter, digit or underscore, and . almost any character. A quantifier says how many times the thing before it repeats: ? 0 or 1 times, * 0 or more, + 1 or more, {9} exactly 9 times, and {2,4} 2 to 4 times. So 7\d{9} means "a 7, then nine digits". Quantifiers are greedy: they take as much as they can.

Classes and quantifiers
<?php
var_dump(preg_match('/\+44/', "+44 7700 900123")); // int(1): \+ is a real plus sign
var_dump(preg_match('/7\d{9}/', "07700900123")); // int(1): a 7 and nine digits
var_dump(preg_match('/7\d{9}/', "07700 900123")); // int(0): the space breaks the digits
var_dump(preg_match('/7\d{3}[ -]?\d{6}/', "07700 900123")); // int(1): an optional space or dash

Anchors and alternatives: without anchors, preg_match() looks for the pattern anywhere, so /7\d{9}/ also matches inside "call 07700900123 after 5". ^ means "the start of the text" and $ "the end" (with one trap that chapter 8 covers). A pipe | means "or", and round brackets group things together: (\+44|0044|0) matches +44, 0044 or 0. Put it all together, and /^(\+44|0044|0)7\d{9}$/ means: from the start, a country code or a 0, then a 7 and nine digits, then the end. The table below lists every piece.

Table — The pattern language
PieceMeansExample
abcExactly these characters/07700/ matches 07700
\+ \. \(A special character as a normal one/\+44/ matches +44
[0-9] [ -]One character from the list/[ -]/ matches a space or a dash
[^0-9]One character that is not in the list/[^0-9]/ matches anything but a digit
\d \s \w .A digit, whitespace, a word character, almost anything/\d\d/ matches 12
? +0 or 1 times, 1 or more times/\d+/ matches 900123
{9} {2,4}Exactly 9 times, 2 to 4 times/7\d{9}/ matches 7700900123
^ $The start, the end of the text/^07/ matches 07 only at the start
a|ba or b/^(\+44|0044|0)/
( ) (?: ) (?<name> )Group and capture, only group, capture by name(?<number>7\d{9})
(?= ) (?! ) (?<= ) (?<! )Followed by, not followed by, comes after, doesn't come after/(?<=£)\d+/ matches 25 in £25
Anchors: the whole text must match
<?php
$pattern = '/^(\+44|0044|0)7\d{9}$/';
foreach (["07700900123", "+447700900123", "00447700900123", "call 07700900123", "0770090012"] as $phone) {
echo str_pad($phone, 18), preg_match($pattern, $phone) ? "valid" : "not valid", "\n";
}
// 07700900123 valid
// +447700900123 valid
// 00447700900123 valid
// call 07700900123 not valid: ^ needs the start of the text
// 0770090012 not valid: only 8 digits after the 7

Capturing groups: round brackets do more than group: they capture. Give preg_match() a third argument, $matches, and PHP fills it with an array: $matches[0] is the whole match, $matches[1] is what the first group matched, $matches[2] the second, and so on. That's how Mia gets the part she needs: the ten digits after the country code or the 0, which she can turn into +44 and those ten digits. A group can also have a name, (?<number>7\d{9}), and then $matches["number"] works too, which reads much better. A group you only need for |, not for its value, is written (?:...); it groups without capturing.

Capturing groups pull parts out
<?php
$phone = "+447700900123";
if (preg_match('/^(\+44|0044|0)(7\d{9})$/', $phone, $matches)) {
print_r($matches);
echo "Rebuilt: +44{$matches[2]}\n";
}
// Array
// (
// [0] => +447700900123
// [1] => +44
// [2] => 7700900123
// )
// Rebuilt: +447700900123
A non-capturing group and a named group
<?php
foreach (["07700900123", "0044 7700900123"] as $phone) {
if (preg_match('/^(?:\+44|0044|0)(?<number>7\d{9})$/', $phone, $matches)) {
echo "+44", $matches["number"], "\n";
} else {
echo "No match: $phone\n";
}
}
// +447700900123
// No match: 0044 7700900123 — the space isn't in the pattern (chapter 8 removes it first)

preg_match_all: preg_match() stops at the first match. preg_match_all() finds every match and returns how many it found. Its $matches holds one list per group: $matches[0] has every whole match, $matches[1] every first group. It's the tool for pulling all the times or all the prices out of a note.

preg_match_all() finds every match
<?php
$note = "Moved from 9:30 to 14:00, then to 16:30";
$count = preg_match_all('/(\d{1,2}):(\d{2})/', $note, $matches);
echo "$count times found\n"; // 3 times found
echo implode(", ", $matches[0]), "\n"; // 9:30, 14:00, 16:30
echo implode(", ", $matches[1]), "\n"; // 9, 14, 16: every first group

Lookarounds: sometimes you need to check what's next to a match without making it part of the match. A lookahead (?=...) means "followed by", and (?!...) "not followed by". A lookbehind (?<=...) means "comes after", and (?<!...) "doesn't come after". For example, /(?<=£)\d+/ finds the digits of a price — digits that come right after a £ sign — without the £ in the match. Lookaheads are also used to check a rule from the start of the text. A booking code of 6 capital letters or digits, with at least one digit, is /^(?=.*\d)[A-Z0-9]{6}$/.

Lookarounds check the neighbours
<?php
$note = "Haircut £25, beard trim £10.50, tip 5";
preg_match_all('/(?<=£)\d+(?:\.\d\d)?/', $note, $matches);
echo implode(" + ", $matches[0]), "\n"; // 25 + 10.50: only the digits after a £
foreach (["AB12CD", "ABCDEF", "ab12cd"] as $code) {
echo $code, ": ", preg_match('/^(?=.*\d)[A-Z0-9]{6}$/', $code) ? "valid" : "not valid", "\n";
}
// AB12CD: valid
// ABCDEF: not valid (no digit)
// ab12cd: not valid (small letters)

Three useful flags: i ignores case. u makes the pattern work with UTF-8 characters instead of bytes; always add it when the text may contain letters like é or ë (chapter 6 again). And x lets you put spaces, new lines and # comments inside the pattern, so a long regex can be read line by line.

The u and x flags
<?php
var_dump(preg_match('/^.{3}$/', "Zoë")); // int(0): without u, . is one byte, and ë is two
var_dump(preg_match('/^.{3}$/u', "Zoë")); // int(1): with u, . is one character
$pattern = '/
^
(?:\+44|0044|0) # the country code, or a 0
(7\d{9}) # a 7 and nine more digits
$
/x';
var_dump(preg_match($pattern, "07700900123")); // int(1)

Key Takeaway

A regular expression describes the shape of text. In PHP it's a string with delimiters and flags, like '/^(\+44|0044|0)7\d{9}$/'. Character classes ([0-9], \d) say which characters, quantifiers (?, +, {9}) say how many, anchors (^, $) pin the start and the end, and round brackets group and capture. preg_match() finds the first match, preg_match_all() finds them all, and lookarounds check the neighbours without matching them.

Why This Matters

Phone numbers, postcodes, booking codes, times in a note: a lot of the text a business receives has a shape. A regular expression describes that shape once, in one line, instead of an if for every way people write it.

Regex is also everywhere outside PHP: in JavaScript, in your code editor's search box, in Laravel's validation rules and in server configuration. The pattern language from this chapter works almost the same way in all of them.

Mia now has a pattern that recognises a UK mobile number in every shape — as long as the spaces, dashes and brackets are gone first — and a group that captures the ten digits she needs. Marcus doesn't tell her yet that the pattern still has a hole. Next: replacing with regex, and turning the pattern into a check you can trust.