TExcelTAD
Home › PHP › PHP Regular Expressions

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:

text
'/colou?r/i'
 │└─────┘│└ flag: i = case-insensitive
 │       └ closing delimiter
 └ opening delimiter

The 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 · try it yourself
<?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 · try it yourself
<?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 · try it yourself
<?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) => '
  

 . ($m[1] * 2),
    'Tea $3, cake $5'
);
echo $doubled . PHP_EOL;

// Split on commas or semicolons with optional spaces
print_r(preg_split('/\s*[,;]\s*/', 'red, green;blue ;  yellow'));
Due: 01/12/2025
too many spaces here
Tea $6, cake $10
Array
(
    [0] => red
    [1] => green
    [2] => blue
    [3] => yellow
)

Validating input

Anchor validation patterns with ^ and $ — otherwise a match anywhere in the string counts. For text containing non-ASCII letters, add the u flag.

php · try it yourself
<?php
$isPostcode = fn(string $s) => preg_match('/^\d{5}$/', $s) === 1;
$isUsername = fn(string $s) => preg_match('/^[a-z][a-z0-9_]{2,15}$/', $s) === 1;

foreach (['70000', '7000', 'abc70000'] as $code) {
    echo str_pad($code, 9) . ($isPostcode($code) ? 'valid' : 'invalid') . PHP_EOL;
}
foreach (['minh_92', '9lives', 'ab'] as $name) {
    echo str_pad($name, 9) . ($isUsername($name) ? 'valid' : 'invalid') . PHP_EOL;
}

echo preg_match_all('/\p{L}+/u', 'Phở bò ngon') . ' words' . PHP_EOL;
70000    valid
7000     invalid
abc70000 invalid
minh_92  valid
9lives   invalid
ab       invalid
3 words

Note: To build a pattern from user input, escape it first with preg_quote($input, '/'). Otherwise characters like . or ( change the meaning of your pattern. For emails and URLs, filter_var() (see the PHP Filters lesson) is usually a better choice than a home-made regex.

Test yourself

What does preg_match() return when the pattern is found?

  1. The matched text
  2. true
  3. 1
  4. The position of the match

Which pattern accepts ONLY strings made of exactly 4 digits?

  1. '/\d{4}/'
  2. '/^\d{4}$/'
  3. '/[0-9]+/'
  4. '/^\d*$/'

In preg_replace('/(\w+)@(\w+)/', '$2 at $1', 'me@home'), what is the result?

  1. me at home
  2. home at me
  3. $2 at $1
  4. me@home