PHP RegEx

Pattern matching and text manipulation with regular expressions

🔍 What is PHP RegEx?

Regular Expressions (RegEx) are patterns used to match, search, and manipulate text. They provide powerful tools for validating emails, extracting data, and performing complex string operations efficiently.


<?php
// Simple pattern matching
$pattern = "/hello/i";
$text = "Hello World";

if(preg_match($pattern, $text)) {
    echo "Match found!";
}
?>
                                    

Output:

Match found!

RegEx Functions

preg_match()

Searches for a pattern in a string and returns true if found. Perfect for validation tasks like checking email formats or password requirements.

<?php
preg_match("/php/i", "I love PHP");
// Returns 1 (true)
?>
🔢

preg_match_all()

Finds all occurrences of a pattern in a string. Useful for extracting multiple matches like finding all email addresses or URLs in text.

<?php
preg_match_all("/\d+/", "I have 2 cats and 3 dogs", $matches);
// $matches = [[2, 3]]
?>
🔄

preg_replace()

Searches for a pattern and replaces it with new text. Great for cleaning data, formatting text, or removing unwanted characters from strings.

<?php
preg_replace("/\s+/", "-", "Hello World");
// Returns "Hello-World"
?>
✂️

preg_split()

Splits a string into an array using a pattern as delimiter. Useful for parsing CSV data, splitting sentences, or breaking text into words.

<?php
preg_split("/[\s,]+/", "apple, banana orange");
// Returns ["apple", "banana", "orange"]
?>

🔹 Basic Pattern Matching

Use preg_match() to check if a pattern exists:

<?php
$text = "I love PHP programming";

// Simple pattern
if(preg_match("/PHP/", $text)) {
    echo "PHP found!<br>";
}

// Case-insensitive search (i modifier)
if(preg_match("/php/i", $text)) {
    echo "php found (case-insensitive)!<br>";
}

// Check if string starts with "I"
if(preg_match("/^I/", $text)) {
    echo "String starts with 'I'<br>";
}

// Check if string ends with "ing"
if(preg_match("/ing$/", $text)) {
    echo "String ends with 'ing'";
}
?>

Output:

PHP found!

php found (case-insensitive)!

String starts with 'I'

String ends with 'ing'

🔹 Common RegEx Patterns

Useful patterns for everyday tasks:

<?php
// Match digits
$pattern1 = "/\d+/"; // One or more digits
preg_match($pattern1, "I have 5 apples", $match);
echo "Number found: " . $match[0] . "<br>";

// Match letters only
$pattern2 = "/^[a-zA-Z]+$/"; // Only letters
if(preg_match($pattern2, "Hello")) {
    echo "Only letters!<br>";
}

// Match email pattern
$pattern3 = "/^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/";
if(preg_match($pattern3, "[email protected]")) {
    echo "Valid email format!<br>";
}

// Match phone number (xxx-xxx-xxxx)
$pattern4 = "/^\d{3}-\d{3}-\d{4}$/";
if(preg_match($pattern4, "123-456-7890")) {
    echo "Valid phone number!";
}
?>

Output:

Number found: 5

Only letters!

Valid email format!

Valid phone number!

🔹 Character Classes

Special characters for matching different types of content:

  • \d - Any digit (0-9)
  • \w - Any word character (letters, digits, underscore)
  • \s - Any whitespace (space, tab, newline)
  • \D - Any non-digit
  • \W - Any non-word character
  • \S - Any non-whitespace
  • . - Any character except newline
<?php
$text = "Phone: 123-456-7890";

// Extract all digits
preg_match_all("/\d/", $text, $digits);
echo "Digits: " . implode("", $digits[0]) . "<br>";

// Extract words
preg_match_all("/\w+/", $text, $words);
echo "Words: " . implode(", ", $words[0]);
?>

Output:

Digits: 1234567890

Words: Phone, 123, 456, 7890

🔹 Quantifiers

Specify how many times a pattern should match:

  • + - One or more times
  • * - Zero or more times
  • ? - Zero or one time
  • {n} - Exactly n times
  • {n,} - At least n times
  • {n,m} - Between n and m times
<?php
// Match 3 digits
if(preg_match("/\d{3}/", "Code: 123")) {
    echo "3 digits found!<br>";
}

// Match 2-4 letters
if(preg_match("/^[a-z]{2,4}$/i", "PHP")) {
    echo "2-4 letters found!<br>";
}

// Match optional 's' at end
if(preg_match("/apples?/", "apple")) {
    echo "'apple' or 'apples' found!<br>";
}

// Match one or more digits
preg_match("/\d+/", "Year 2024", $match);
echo "Number: " . $match[0];
?>

Output:

3 digits found!

2-4 letters found!

'apple' or 'apples' found!

Number: 2024

🔹 preg_match_all()

Find all matches in a string:

<?php
$text = "Contact us: [email protected] or [email protected]";

// Find all email addresses
$pattern = "/[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/";
preg_match_all($pattern, $text, $emails);

echo "Emails found: " . count($emails[0]) . "<br>";
foreach($emails[0] as $email) {
    echo "- $email<br>";
}

// Find all numbers
$text2 = "I have 2 cats, 3 dogs, and 5 birds";
preg_match_all("/\d+/", $text2, $numbers);
echo "<br>Numbers: " . implode(", ", $numbers[0]);
?>

Output:

Emails found: 2

- [email protected]

- [email protected]


Numbers: 2, 3, 5

🔹 preg_replace()

Search and replace using patterns:

<?php
// Replace spaces with hyphens
$text1 = "Hello World PHP";
$result1 = preg_replace("/\s+/", "-", $text1);
echo $result1 . "<br>";

// Remove all digits
$text2 = "Product123 costs $45.99";
$result2 = preg_replace("/\d+/", "", $text2);
echo $result2 . "<br>";

// Replace multiple spaces with single space
$text3 = "Too    many     spaces";
$result3 = preg_replace("/\s+/", " ", $text3);
echo $result3 . "<br>";

// Remove special characters
$text4 = "Hello@#$World!";
$result4 = preg_replace("/[^a-zA-Z0-9\s]/", "", $text4);
echo $result4;
?>

Output:

Hello-World-PHP

Product costs $.

Too many spaces

HelloWorld

🔹 preg_split()

Split strings using patterns:

<?php
// Split by spaces or commas
$text1 = "apple, banana orange, grape";
$fruits = preg_split("/[\s,]+/", $text1);
echo "Fruits: " . implode(" | ", $fruits) . "<br><br>";

// Split by multiple delimiters
$text2 = "one;two:three,four";
$items = preg_split("/[;:,]/", $text2);
echo "Items: " . implode(" - ", $items) . "<br><br>";

// Split by whitespace
$text3 = "Hello    World   PHP";
$words = preg_split("/\s+/", $text3);
echo "Words: " . implode(", ", $words);
?>

Output:

Fruits: apple | banana | orange | grape


Items: one - two - three - four


Words: Hello, World, PHP

🔹 Practical Example: Form Validation

Validate user input using RegEx:

<?php
function validateEmail($email) {
    $pattern = "/^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/";
    return preg_match($pattern, $email);
}

function validatePhone($phone) {
    $pattern = "/^\d{3}-\d{3}-\d{4}$/";
    return preg_match($pattern, $phone);
}

function validatePassword($password) {
    // At least 8 chars, 1 uppercase, 1 lowercase, 1 digit
    $pattern = "/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d).{8,}$/";
    return preg_match($pattern, $password);
}

// Test validations
$email = "[email protected]";
$phone = "123-456-7890";
$password = "Pass1234";

echo "Email valid: " . (validateEmail($email) ? "Yes" : "No") . "<br>";
echo "Phone valid: " . (validatePhone($phone) ? "Yes" : "No") . "<br>";
echo "Password valid: " . (validatePassword($password) ? "Yes" : "No");
?>

Output:

Email valid: Yes

Phone valid: Yes

Password valid: Yes

💡 RegEx Tips:

  • Test Patterns: Use online RegEx testers to debug patterns
  • Escape Special Characters: Use backslash (\) before special chars
  • Use Modifiers: i (case-insensitive), m (multiline), s (dotall)
  • Keep it Simple: Complex patterns are hard to maintain
  • Validate User Input: Always validate data from users

🧠 Test Your Knowledge

Which function finds all matches of a pattern in a string?