PHP Regular Expressions
A regular expression (regex) is a small pattern language for describing text: "three digits, a dash, four digits", "a word that starts with a capital letter", "anything between square brackets". PHP uses the PCRE engine (Perl Compatible Regular Expressions) through a set of functions whose names start with preg_.
Writing a pattern
In PHP a pattern is a string that contains a delimiter, the expression and optional flags:
'/colou?r/i'
│└─────┘│└ flag: i = case-insensitive
│ └ closing delimiter
└ opening delimiterThe slash is the usual delimiter, but #, ~ or {} also work — handy when the pattern itself contains slashes: '#^/blog/\d+$#'. Use single quotes for patterns so PHP does not interpret backslashes like \d or $ first.
The main functions
| Function | Purpose | Returns |
|---|---|---|
preg_match($p, $s, $m) |
find the first match | 1 or 0 (and fills $m) |
preg_match_all($p, $s, $m) |
find every match | number of matches |
preg_replace($p, $r, $s) |
replace matches | the new string |
preg_replace_callback($p, $fn, $s) |
replace using a function | the new string |
preg_split($p, $s) |
split on matches | array of pieces |
preg_quote($s, '/') |
escape special characters in user text | escaped string |
Matching and capturing
Parentheses create capture groups. preg_match() stores the whole match in $m[0] and each group in $m[1], $m[2], … Named groups (?<name>…) are also available under their name.
<?php
$log = 'Order #4521 shipped on 2025-03-14 to Da Nang';
if (preg_match('/#(\d+)/', $log, $m)) {
echo "Order number: {$m[1]}" . PHP_EOL;
}
$pattern = '/(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/';
if (preg_match($pattern, $log, $d)) {
echo "Day {$d['day']}, month {$d['month']}, year {$d['year']}" . PHP_EOL;
}
var_dump(preg_match('/refund/i', $log));Order number: 4521
Day 14, month 03, year 2025
int(0)
Finding every match
<?php
$text = 'Contact sales@tad.example or help@tad.example, not info@other.test';
$count = preg_match_all('/\b([a-z]+)@tad\.example\b/', $text, $matches);
echo "Found $count addresses" . PHP_EOL;
print_r($matches[1]);
preg_match_all('/\d+/', 'Room 12, floor 3, building 207', $nums);
echo array_sum($nums[0]) . PHP_EOL;Found 2 addresses
Array
(
[0] => sales
[1] => help
)
222
$matches[0] holds the full matches and $matches[1] the first group of each match.
Pattern cheat sheet
| Token | Matches |
|---|---|
. |
any character except a newline |
\d \w \s |
digit, word character (a-z A-Z 0-9 _), whitespace |
\D \W \S |
the opposite of each |
[abc] [^abc] [a-z] |
one of, none of, a range |
^ $ |
start / end of the string (or line with m) |
\b |
word boundary |
* + ? |
0+, 1+, 0 or 1 times |
{3} {2,5} |
exactly 3, between 2 and 5 times |
a|b |
a or b |
( ) (?: ) |
capturing / non-capturing group |
| Flag | Meaning |
|---|---|
i |
case-insensitive |
m |
^ and $ match at every line |
s |
. also matches newlines |
x |
ignore whitespace in the pattern (allows comments) |
u |
treat pattern and subject as UTF-8 |
Tip: Quantifiers are greedy:
.+grabs as much as it can. Add?to make them lazy —<.+?>matches a single HTML tag instead of everything from the first<to the last>.
Replacing and splitting
preg_replace() can refer to groups in the replacement as $1, $2, … For logic that a plain replacement cannot express, preg_replace_callback() calls your function for every match.
<?php
// Reformat dates from YYYY-MM-DD to DD/MM/YYYY
echo preg_replace('/(\d{4})-(\d{2})-(\d{2})/', '$3/$2/$1', 'Due: 2025-12-01') . PHP_EOL;
// Collapse runs of whitespace into one space
echo preg_replace('/\s+/', ' ', "too many \t spaces\nhere") . PHP_EOL;
// Double every price in the text
$doubled = preg_replace_callback(
'/\$(\d+)/',
fn(array $m) => '