Regular Expressions in PHP
Master pattern matching and text manipulation in PHP using preg_match(), preg_replace(), and preg_split() with practical regex patterns.
Introduction to Regular Expressions
PHP uses Perl-Compatible Regular Expressions (PCRE) via the preg_* family of functions. A regex is a pattern that matches strings — used for validation, search, replace, and extraction.
1. What is a Regular Expression?
Pattern-based string matching.
2. Delimiters
Any non-alphanumeric, non-whitespace character can be a delimiter.
Regex Flags (Modifiers)
Flags are placed after the closing delimiter and modify matching behaviour.
1. Common Flags
i, m, s, x modifiers.
Character Classes
Character classes let you match any character from a defined set.
1. Shorthand Classes
\d \w \s and their negations.
2. Custom Character Classes
Use [abc] and [a-z] ranges.
Quantifiers
Quantifiers control repetition of tokens in a pattern.
1. Common Quantifiers
* + ? {n,m}
2. Greedy vs Lazy
Add ? after quantifier for lazy (non-greedy) match.
Anchors & Boundaries
Anchors assert position in the string without consuming characters.
1. ^ and $ Anchors
Match start and end of string.
2. Word Boundary \b
Match at the edge of a word.
Groups & Alternation
Groups let you capture parts of a match or apply quantifiers to sequences.
1. Capturing Groups
Use () to capture submatches.
2. Named Capturing Groups (PHP 5.2+)
Use (?P<name>...) for readable captures.
3. Non-Capturing Groups
Use (?:...) to group without capturing.
4. Alternation (OR)
Use | to match one of several options.
preg_* Functions
PHP provides several preg_* functions for different regex operations.
1. preg_match() — Single Match
Find first match and capture groups.
2. preg_match_all() — All Matches
Find every match in the string.
3. preg_replace() — Replace
Replace matches with a string.
4. preg_replace_callback() — Dynamic Replace
Use a callback to build replacement strings.
5. preg_split() — Split
Split a string by a regex pattern.
Lookahead & Lookbehind
Lookahead and lookbehind let you match patterns only when preceded or followed by another pattern.
1. Lookahead (?=...) and (?!...)
Assert what follows the match.
2. Lookbehind (?<=...) and (?<!...)
Assert what precedes the match.
Common Validation Patterns
Regex is the standard approach for validating emails, URLs, phone numbers, and more in PHP.
1. Email Validation
Practical email pattern.
2. Phone Number Validation
Match common phone formats.
3. Password Strength Check
Validate minimum password requirements.