RegEx Patterns
A regular expression pattern is built from small pieces: literal characters, character classes, quantifiers, anchors, groups, and assertions. This lesson explains each building block with a short example, so you can both write patterns and read patterns written by others.
Literal Characters and Metacharacters
Most characters match themselves: the pattern /cat/ finds the text cat. A few characters have special meaning — these are the metacharacters:
. ^ $ * + ? { } [ ] \ | ( )
To match a metacharacter literally, escape it with a backslash:
<?php
var_dump(preg_match('/1.5/', '1x5')); // . matches any character
var_dump(preg_match('/1\.5/', '1x5')); // \. matches only a dot
var_dump(preg_match('/1\.5/', '1.5'));
Output
int(1)
int(0)
int(1)
The unescaped dot matched x, which is a common source of overly permissive patterns — for example, /example.com/ also matches exampleXcom.
Character Classes [...]
A character class matches one character from a set:
| Pattern | Matches |
|---|---|
[aeiou] | One vowel |
[a-z] | One lowercase ASCII letter |
[A-Za-z0-9] | One letter or digit |
[^0-9] | One character that is not a digit (^ at the start negates) |
[-.] or [. 0 ] | A hyphen or a dot |
Inside a class, most metacharacters lose their special meaning: [.] matches a literal dot. Only ],