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):
<?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
<?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.2026preg_split
<?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-worldTest yourself
Which function finds ALL matches of a pattern?
preg_match()preg_match_all()preg_find()preg_grep_all()
Show answer
Answer: preg_match_all()
Practice next
- Slugify a Title (Strings & Regex) · coding problem