Lessons → PHP Regular Expressions

PHP Regular Expressions

PHP
⏱ 22 min read📖 IntermediateNot completed

Regular expressions (regex) are powerful patterns for searching, validating, and manipulating text. They look confusing at first but become invaluable once you learn the basics.

Basic Regex Functions in PHP

FunctionPurpose
preg_match()Check if pattern matches (returns 1 or 0)
preg_match_all()Find ALL matches
preg_replace()Replace matches with new text
preg_split()Split string by pattern
preg_grep()Filter array by pattern

Basic Syntax

PHP
<?php
// Pattern format: /pattern/flags
// Delimiters are usually / / but can be # # or ~ ~

$str = "Hello, World! PHP is great.";

// Basic match
preg_match('/PHP/', $str, $matches);
// $matches[0] = "PHP"

// Case-insensitive match (i flag)
preg_match('/php/i', $str, $matches);
// $matches[0] = "PHP"

// Find all matches
preg_match_all('/\w+/', $str, $matches);
// $matches[0] = ["Hello", "World", "PHP", "is", "great"]
?>

Character Classes & Shortcuts

PatternMatchesExample
.Any character (except newline)h.t → "hat", "hot", "hit"
\dAny digit [0-9]\d\d\d → "123"
\DNon-digit
\wWord char [a-zA-Z0-9_]
\WNon-word char
\sWhitespace
\SNon-whitespace
[abc]a, b, or c
[^abc]NOT a, b, or c
[a-z]Any lowercase letter

Quantifiers

PHP — Quantifiers
<?php
// * = 0 or more
// + = 1 or more
// ? = 0 or 1 (optional)
// {n} = exactly n times
// {n,} = n or more times
// {n,m} = between n and m times

preg_match('/\d+/', 'abc123def', $m);   // "123"
preg_match('/\d{3}/', 'Phone: 090', $m); // "090"
preg_match('/colou?r/', 'color', $m);    // matches "color" AND "colour"

// ^ = start of string, $ = end of string
preg_match('/^\d+$/', '12345', $m);  // matches (only digits)
preg_match('/^\d+$/', '123ab', $m);  // no match (has letters)
?>

Real-World Examples

PHP — Validation
<?php
// Email validation
function isValidEmail(string $email): bool {
    return (bool) preg_match('/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/', $email);
}
isValidEmail('user@example.com');  // true
isValidEmail('invalid-email');     // false

// Japanese phone number
function isJapanesePhone(string $phone): bool {
    return (bool) preg_match('/^(0\d{1,4}-?\d{1,4}-?\d{4}|080|090|070\d{8})$/', $phone);
}

// Password strength (min 8 chars, 1 uppercase, 1 number)
function isStrongPassword(string $password): bool {
    return (bool) preg_match('/^(?=.*[A-Z])(?=.*\d).{8,}$/', $password);
}

// URL validation
function isValidUrl(string $url): bool {
    return (bool) preg_match('/^https?:\/\/[^\s\/$.?#].[^\s]*$/', $url);
}

// Extract all URLs from text
$text = "Visit https://laravel.com and https://php.net for docs.";
preg_match_all('/https?:\/\/\S+/', $text, $matches);
// $matches[0] = ["https://laravel.com", "https://php.net"]
?>

preg_replace — Find & Replace

PHP
<?php
// Remove all non-digits (clean phone number)
$phone = preg_replace('/[^0-9]/', '', '090-1234-5678');
echo $phone;  // 09012345678

// Convert URLs to clickable links
$text = "Visit https://laravel.com for docs";
$linked = preg_replace(
    '/(https?:\/\/\S+)/',
    '<a href="$1">$1</a>',
    $text
);

// Remove HTML tags
$clean = preg_replace('/<[^>]+>/', '', '<p>Hello <b>World</b></p>');
echo $clean;  // Hello World

// Convert snake_case to camelCase
$camel = preg_replace_callback('/_([a-z])/', fn($m) => strtoupper($m[1]), 'my_variable_name');
echo $camel;  // myVariableName
?>

Named Groups

PHP
<?php
// Named capture groups with (?P<name>pattern)
$date = "Today is 2025-05-22";
preg_match('/(?P<year>\d{4})-(?P<month>\d{2})-(?P<day>\d{2})/', $date, $m);

echo $m['year'];   // 2025
echo $m['month'];  // 05
echo $m['day'];    // 22

// Parse log line
$log = '[2025-05-22 14:30:45] ERROR: Connection failed';
preg_match('/\[(?P<date>[^\]]+)\] (?P<level>\w+): (?P<message>.+)/', $log, $m);

echo $m['date'];     // 2025-05-22 14:30:45
echo $m['level'];    // ERROR
echo $m['message'];  // Connection failed
?>
💡
Test regex at regex101.com! This free tool lets you test and debug regex patterns in real-time with explanations. Always test your patterns there before using them in production code.
💡
Don't use regex for everything! For emails and URLs, PHP has built-in filter_var($email, FILTER_VALIDATE_EMAIL) which is more reliable than custom regex. Use regex for custom patterns that PHP doesn't support natively.
🧠

Test your knowledge!

Take a quiz to reinforce what you learned.

Take Quiz →