🔍 PHP Regular Expressions: The Pattern Detective
Imagine you’re a detective with a magical magnifying glass. This glass can find ANY pattern in a book—names, phone numbers, secret codes—anything! Regular expressions are your magnifying glass for text.
🎯 What Are Regular Expressions?
Think of regular expressions (regex) like a search filter on steroids.
Normal search: Find the word “cat” Regex search: Find anything that looks like a phone number, email, or date—even if you don’t know the exact text!
// Normal search - finds exact match
strpos("I have a cat", "cat"); // âś“ Found!
// Regex search - finds ANY 3-digit number
preg_match("/\d{3}/", "Call 555-1234"); // âś“ Found 555!
đź§± Regular Expression Basics
The Two Delimiters
Every regex pattern in PHP lives between delimiters—like bookends for your pattern:
"/pattern/" // Forward slashes (most common)
"#pattern#" // Hash marks (useful when / is in pattern)
"~pattern~" // Tildes (another option)
Your First Pattern Match
$text = "I love pizza!";
if (preg_match("/pizza/", $text)) {
echo "Yum! Found pizza!";
}
// Output: Yum! Found pizza!
What happened?
/pizza/= Look for the word “pizza”preg_match()= PHP’s regex search function- Returns
1(true) if found,0(false) if not
🎨 Regular Expression Patterns
📌 Basic Pattern Characters
| Pattern | Meaning | Example Match |
|---|---|---|
. |
Any single character | c.t → cat, cot, cut |
\d |
Any digit (0-9) | \d\d\d → 123, 456 |
\w |
Any word character | \w+ → hello, PHP8 |
\s |
Any whitespace | a\sb → “a b” |
^ |
Start of string | ^Hello → “Hello world” |
$ |
End of string | world$ → “Hello world” |
📌 Quantifiers (How Many?)
graph TD A["Quantifiers"] --> B["* = Zero or more"] A --> C["+ = One or more"] A --> D["? = Zero or one"] A --> E["{n} = Exactly n times"] A --> F["{n,m} = Between n and m"]
Examples:
// * = Zero or more
preg_match("/ab*c/", "ac"); // âś“ (zero b's)
preg_match("/ab*c/", "abbbc"); // âś“ (three b's)
// + = One or more
preg_match("/ab+c/", "ac"); // âś— (needs at least 1 b)
preg_match("/ab+c/", "abc"); // âś“ (one b)
// {n,m} = Between n and m
preg_match("/\d{3,5}/", "1234"); // âś“ (4 digits)
📌 Character Classes (Pick One From Group)
Character classes let you say “match any ONE of these characters”:
// [abc] = Match a, b, OR c
preg_match("/[aeiou]/", "hello"); // âś“ Finds 'e'
// [0-9] = Any digit (same as \d)
preg_match("/[0-9]+/", "Room 42"); // âś“ Finds 42
// [A-Za-z] = Any letter
preg_match("/[A-Za-z]+/", "PHP8"); // âś“ Finds PHP
// [^abc] = NOT a, b, or c
preg_match("/[^0-9]/", "R2D2"); // âś“ Finds R
📌 Groups and Alternation
Groups () = Capture parts of a match
Alternation | = This OR that
// Alternation: cat OR dog
preg_match("/cat|dog/", "I love dogs"); // âś“ Finds dog
// Groups: Capture the match
preg_match("/(\d{3})-(\d{4})/", "555-1234", $m);
echo $m[1]; // 555
echo $m[2]; // 1234
📌 Special Escape Characters
// To match actual special characters, escape them
preg_match("/\./", "file.txt"); // Match literal dot
preg_match("/\$/", "$100"); // Match dollar sign
preg_match("/\?/", "Really?"); // Match question mark
đź”§ Regular Expression Functions
PHP gives you powerful tools to work with regex:
graph TD A["PHP Regex Functions"] --> B["preg_match#40;#41;<br/>Find first match"] A --> C["preg_match_all#40;#41;<br/>Find ALL matches"] A --> D["preg_replace#40;#41;<br/>Search & replace"] A --> E["preg_split#40;#41;<br/>Split string by pattern"]
🔍 preg_match() — Find First Match
$email = "contact@example.com";
$pattern = "/[a-z]+@[a-z]+\.[a-z]+/";
if (preg_match($pattern, $email)) {
echo "Valid email format!";
}
With captures:
$text = "My age is 25 years";
preg_match("/age is (\d+)/", $text, $matches);
echo $matches[0]; // "age is 25" (full match)
echo $matches[1]; // "25" (captured group)
🔍 preg_match_all() — Find ALL Matches
$text = "Prices: $10, $25, $99";
preg_match_all("/\$(\d+)/", $text, $matches);
print_r($matches[1]);
// Array: [10, 25, 99]
🔄 preg_replace() — Search and Replace
// Replace all digits with X
$phone = "555-123-4567";
echo preg_replace("/\d/", "X", $phone);
// Output: XXX-XXX-XXXX
// Use captured groups in replacement
$name = "Smith, John";
echo preg_replace("/(\w+), (\w+)/", "$2 $1", $name);
// Output: John Smith
✂️ preg_split() — Split by Pattern
// Split by any whitespace
$text = "apple banana\tcherry";
$fruits = preg_split("/\s+/", $text);
// Array: [apple, banana, cherry]
// Split by comma OR semicolon
$data = "a,b;c,d";
$parts = preg_split("/[,;]/", $data);
// Array: [a, b, c, d]
🎯 Pattern Modifiers
Add these after the closing delimiter to change behavior:
// i = Case-insensitive
preg_match("/hello/i", "HELLO"); // âś“ Matches!
// m = Multiline (^ and $ match line starts/ends)
preg_match("/^line/m", "first\nline two"); // âś“
// s = Dot matches newlines too
preg_match("/a.b/s", "a\nb"); // âś“ Matches!
// Combine modifiers
preg_match("/hello world/is", "HELLO\nWORLD"); // âś“
🌟 Real-World Examples
Validate an Email
$pattern = "/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/";
preg_match($pattern, "user@site.com"); // âś“
preg_match($pattern, "bad-email"); // âś—
Extract Hashtags
$tweet = "Learning #PHP and #regex is fun!";
preg_match_all("/#(\w+)/", $tweet, $tags);
print_r($tags[1]); // [PHP, regex]
Clean Phone Number
$phone = "(555) 123-4567";
$clean = preg_replace("/[^0-9]/", "", $phone);
echo $clean; // 5551234567
Find URLs
$text = "Visit https://example.com today!";
preg_match("/https?:\/\/[^\s]+/", $text, $url);
echo $url[0]; // https://example.com
đź§ Quick Memory Tips
.= Any character (like a wildcard card in a game)*= Zero or more (optional, greedy)+= One or more (required, greedy)?= Optional (zero or one)\d= Digit (0-9)\w= Word character (letters, numbers, underscore)[]= Choose one from the set()= Capture group (save for later)|= OR (this or that)
🚀 You Did It!
You now have the magical magnifying glass of PHP! Regular expressions might look scary at first—like a secret code—but they’re just patterns describing what you want to find.
Start simple. Build up. Practice often.
The more you use regex, the more powerful your text-searching superpowers become! 🦸‍♂️
