PHP Regular Expressions
PHP uses PCRE (Perl-Compatible Regex). All regex functions start with preg_. Patterns are strings with delimiters around them (usually /).
The main functions
| Function | Does |
|---|---|
preg_match($pattern, $s, $matches) | First match; sets $matches if found. |
preg_match_all($pattern, $s, $matches) | All matches. |
preg_replace($pattern, $replace, $s) | Replace. |
preg_replace_callback | Replace each match via a function. |
preg_split($pattern, $s) | Split. |
preg_quote($s) | Escape regex metachars in a literal string. |
Quick examples
PHP
// Find all email addresses
preg_match_all('/[\w.+-]+@[\w.-]+/', $text, $matches);
print_r($matches[0]);
// Whole-string check
if (preg_match('/^\d{4}-\d{2}-\d{2}$/', $date)) {
echo 'ISO date';
}
// Replace with named groups
$result = preg_replace_callback(
'/(?<user>\w+)@(?<host>[\w.]+)/',
fn($m) => "[{$m['user']} at {$m['host']}]",
$text
);
Common pattern atoms
| Atom | Matches |
|---|---|
\d \D \w \W \s \S | Digit, word char, whitespace (and not). |
^ $ | Start, end of string. |
\b | Word boundary. |
. | Any char except newline. |
[abc] / [^abc] / [a-z] | Char class / negation / range. |
Modifiers (after the closing delimiter)
| Flag | Means |
|---|---|
i | Case-insensitive. |
m | ^ and $ match line ends. |
s | . matches newlines. |
u | UTF-8 mode. |
x | Verbose — allows whitespace and # comments inside the pattern. |
Tip: If your pattern contains
/, switch the delimiter to # or ~ instead of escaping: '#https?://example\.com#'.Example
Example
<?php
$text = 'Email Ada at ada@example.com or ada@old.org';
preg_match_all('/[\w.+-]+@[\w.-]+/', $text, $m);
print_r($m[0]);
Try it Yourself »
Exercise
Function for finding all matches.
('/[\w.+-]+@[\w.-]+/', $text, $m)
snake_case; 14 chars.
Discussion
Loading…