PHP Tutorial · PHP for the Web · Lesson 27 of 38

PHP Regular Expressions

Match, extract and replace text with preg_ functions.

preg_match

PHP uses PCRE regular expressions, written between delimiters like /.../ with flags after (i case-insensitive, u Unicode):

Example 1Try it yourself
<?php
var_dump(preg_match('/^\d{5}$/', "90210"));
if (preg_match('/(?<year>\d{4})-(?<month>\d{2})/', "Released 2026-10", $m)) {
    echo $m["year"], " / ", $m["month"], "\n";
}

Output

int(1)
2026 / 10

preg_match_all and preg_replace

Example 2Try it yourself
<?php
$text = "Contact [email protected] or [email protected]";
preg_match_all('/[\w.+-]+@[\w-]+\.\w+/', $text, $matches);
print_r($matches[0]);
echo preg_replace('/\s+/', " ", "too    many   spaces"), "\n";
echo preg_replace('/(\d{4})-(\d{2})-(\d{2})/', '$3.$2.$1', "2026-10-12"), "\n";

Output

Array
(
    [0] => [email protected]
    [1] => [email protected]
)
too many spaces
12.10.2026

preg_split

Example 3Try it yourself
<?php
print_r(preg_split('/[\s,;]+/', "red, green;blue  yellow"));
$slug = strtolower(trim(preg_replace('/[^A-Za-z0-9]+/', "-", "Hello, PHP World!"), "-"));
echo $slug, "\n";

Output

Array
(
    [0] => red
    [1] => green
    [2] => blue
    [3] => yellow
)
hello-php-world

Test yourself

Which function finds ALL matches of a pattern?

  1. preg_match()
  2. preg_match_all()
  3. preg_find()
  4. preg_grep_all()
Show answer

Answer: preg_match_all()

Practice next