PHP Regular Expressions
ExamplePHP
<?php
$text = "Contact ada@example.com or sam@wecode.org by 2026-11-04.";
echo preg_match('/\d{4}-\d{2}-\d{2}/', $text, $m), " ", $m[0], "\n";
preg_match_all('/[\w.]+@[\w.]+\.\w+/', $text, $emails);
print_r($emails[0]);
echo preg_replace('/\s+/', " ", "too many spaces"), "\n";
echo preg_replace('/(\w+)@(\w+)/', '$2 at $1', "ada@example"), "\n";
print_r(preg_split('/[\s,]+/', "a, b c,d"));
var_dump(preg_match('/^[A-Z][a-z]+$/', "Hello"));Output
1 2026-11-04
Array
(
[0] => ada@example.com
[1] => sam@wecode.org
)
too many spaces
example at ada
Array
(
[0] => a
[1] => b
[2] => c
[3] => d
)
int(1)Regular expressions are patterns for matching text. preg_match finds the first match, preg_match_all all of them, and preg_replace substitutes.
Quick check
Which function replaces text matching a pattern?
Finish the quick check (and any code exercise) to complete this lesson, or mark it done yourself.
Tip: use the left and right arrow keys to move between lessons.