PHP RegEx

Pattern matching with regular expressions

🔍 What is RegEx?

Regular Expressions (RegEx) are patterns used to match, search, and manipulate text. PHP provides powerful functions to work with regex for validation, searching, and text replacement.


<?php
// Simple pattern matching
$pattern = "/hello/i";
$text = "Hello World";
echo preg_match($pattern, $text); // Output: 1 (match found)
?>
                                    

Key RegEx Functions

Match

Find pattern matches

preg_match($pattern, $text);
🔄

Replace

Replace matched patterns

preg_replace($pattern, $replace, $text);
✂️

Split

Split string by pattern

preg_split($pattern, $text);
📋

Match All

Find all matches

preg_match_all($pattern, $text, $matches);

🔹 Basic Pattern Matching

Use preg_match() to check if a pattern exists in a string. It returns 1 if found, 0 if not found, and false on error.

<?php
$text = "The quick brown fox";
$pattern = "/quick/";

if (preg_match($pattern, $text)) {
    echo "Match found!";
} else {
    echo "No match found.";
}

// Case-insensitive matching
$pattern2 = "/QUICK/i";
echo "<br>Case-insensitive: " . (preg_match($pattern2, $text) ? "Found" : "Not found");
?>

Output:

Match found!
Case-insensitive: Found

🔹 Email Validation

Validate email addresses using regex patterns. This checks for proper email format with username, @ symbol, domain name, and extension.

<?php
$email = "[email protected]";
$pattern = "/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/";

if (preg_match($pattern, $email)) {
    echo "Valid email address";
} else {
    echo "Invalid email address";
}

// Test invalid email
$invalid = "invalid.email@";
echo "<br>" . $invalid . ": " . (preg_match($pattern, $invalid) ? "Valid" : "Invalid");
?>

Output:

Valid email address
invalid.email@: Invalid

🔹 Find and Replace

Replace text matching a pattern with new content using preg_replace(). This is useful for cleaning data, formatting text, or censoring content.

<?php
$text = "I love apples and apples are great!";
$pattern = "/apples/i";
$replacement = "oranges";

$result = preg_replace($pattern, $replacement, $text);
echo $result;

// Replace multiple patterns
$text2 = "Call me at 123-456-7890 or 098-765-4321";
$pattern2 = "/\d{3}-\d{3}-\d{4}/";
$result2 = preg_replace($pattern2, "[REDACTED]", $text2);
echo "<br>" . $result2;
?>

Output:

I love oranges and oranges are great!
Call me at [REDACTED] or [REDACTED]

🔹 Extract All Matches

Use preg_match_all() to find all occurrences of a pattern in a string. The matches are stored in an array for further processing.

<?php
$text = "Contact us at [email protected] or [email protected]";
$pattern = "/[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/";

preg_match_all($pattern, $text, $matches);

echo "Found " . count($matches[0]) . " email(s):<br>";
foreach ($matches[0] as $email) {
    echo "- " . $email . "<br>";
}
?>

Output:

Found 2 email(s):
- [email protected]
- [email protected]

🔹 Split String by Pattern

Split strings using regex patterns instead of fixed delimiters. This allows flexible splitting based on complex patterns like multiple spaces or special characters.

<?php
$text = "apple,banana;orange|grape";
$pattern = "/[,;|]/"; // Split by comma, semicolon, or pipe

$fruits = preg_split($pattern, $text);

echo "Fruits:<br>";
foreach ($fruits as $fruit) {
    echo "- " . $fruit . "<br>";
}
?>

Output:

Fruits:
- apple
- banana
- orange
- grape

🔹 Common RegEx Patterns

Here are frequently used regex patterns for validation and text processing. These patterns cover common scenarios like phone numbers, URLs, and dates.

<?php
// Phone number (US format)
$phone = "123-456-7890";
$phonePattern = "/^\d{3}-\d{3}-\d{4}$/";
echo "Phone: " . (preg_match($phonePattern, $phone) ? "Valid" : "Invalid");

// URL validation
$url = "https://www.example.com";
$urlPattern = "/^https?:\/\/[\w\-]+(\.[\w\-]+)+[/#?]?.*$/";
echo "<br>URL: " . (preg_match($urlPattern, $url) ? "Valid" : "Invalid");

// Date (YYYY-MM-DD)
$date = "2024-12-25";
$datePattern = "/^\d{4}-\d{2}-\d{2}$/";
echo "<br>Date: " . (preg_match($datePattern, $date) ? "Valid" : "Invalid");
?>

Output:

Phone: Valid
URL: Valid
Date: Valid

🔹 Capturing Groups

Extract specific parts of matched patterns using parentheses to create capturing groups. This is useful for parsing structured data like dates or names.

<?php
$text = "Born on 1990-05-15";
$pattern = "/(\d{4})-(\d{2})-(\d{2})/";

if (preg_match($pattern, $text, $matches)) {
    echo "Full date: " . $matches[0] . "<br>";
    echo "Year: " . $matches[1] . "<br>";
    echo "Month: " . $matches[2] . "<br>";
    echo "Day: " . $matches[3];
}
?>

Output:

Full date: 1990-05-15
Year: 1990
Month: 05
Day: 15

🧠 Test Your Knowledge

Which function finds all pattern matches in a string?