iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

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

FunctionDoes
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_callbackReplace 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

AtomMatches
\d \D \w \W \s \SDigit, word char, whitespace (and not).
^ $Start, end of string.
\bWord boundary.
.Any char except newline.
[abc] / [^abc] / [a-z]Char class / negation / range.

Modifiers (after the closing delimiter)

FlagMeans
iCase-insensitive.
m^ and $ match line ends.
s. matches newlines.
uUTF-8 mode.
xVerbose — 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)

Test yourself

Q1. PHP regex functions begin with…
Q2. Patterns are…
Q3. Multiple matches use…

Discussion

Loading…