Tutorials Logic, IN +91 8092939553 info@tutorialslogic.com
FAQs Support
Navigation
Home About Us Contact Us Blogs FAQs
Tutorials
All Tutorials
Services
Academic Projects Resume Writing Interview Questions Website Development
Compiler Tutorials

PHP Regular Expressions

Regular expressions (regex) are patterns used to match, search, and manipulate strings. PHP uses PCRE (Perl Compatible Regular Expressions) via the preg_* functions.

preg_match() and preg_match_all()

preg_match() checks if a pattern exists in a string (returns 1 or 0). preg_match_all() finds all matches.

preg_match and preg_match_all
<?php
$str = "The price is $42.50 and $18.99";

// preg_match — find first match
if (preg_match('/\$(\d+\.\d{2})/', $str, $matches)) {
    echo "First price: " . $matches[0]; // $42.50
    echo "Amount: "      . $matches[1]; // 42.50
}

// preg_match_all — find all matches
$count = preg_match_all('/\$(\d+\.\d{2})/', $str, $all);
echo "Found $count prices\n";
print_r($all[1]); // [42.50, 18.99]

// Validate email
$email = "user@example.com";
if (preg_match('/^[a-zA-Z0-9._%+\-]+@[a-zA-Z0-9.\-]+\.[a-zA-Z]{2,}$/', $email)) {
    echo "Valid email";
}

// Case-insensitive match (i modifier)
if (preg_match('/hello/i', "Hello World")) {
    echo "Found (case-insensitive)";
}
?>

preg_replace() and preg_split()

preg_replace() replaces matches with a replacement string. preg_split() splits a string by a regex pattern.

preg_replace and preg_split
<?php
// preg_replace — replace pattern with string
$text = "Hello   World   PHP";
$clean = preg_replace('/\s+/', ' ', $text); // collapse whitespace
echo $clean; // Hello World PHP

// Replace with backreference
$date = "2024-01-15";
$formatted = preg_replace('/(\d{4})-(\d{2})-(\d{2})/', '$3/$2/$1', $date);
echo $formatted; // 15/01/2024

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

// preg_split — split by pattern
$csv = "one, two,  three ,four";
$parts = preg_split('/\s*,\s*/', trim($csv));
print_r($parts); // [one, two, three, four]

// Split on multiple delimiters
$str = "apple;banana|cherry,date";
$fruits = preg_split('/[;|,]/', $str);
print_r($fruits); // [apple, banana, cherry, date]
?>

Common Patterns and Modifiers

Common Regex Patterns
<?php
// Common patterns
$patterns = [
    'digits only'     => '/^\d+$/',
    'alphanumeric'    => '/^[a-zA-Z0-9]+$/',
    'phone (US)'      => '/^\+?1?\s?\(?\d{3}\)?[\s.\-]?\d{3}[\s.\-]?\d{4}$/',
    'URL'             => '/^https?:\/\/[\w\-]+(\.[\w\-]+)+([\w\-\._~:\/\?#\[\]@!\$&\'\(\)\*\+,;=.]+)?$/',
    'IPv4'            => '/^(\d{1,3}\.){3}\d{1,3}$/',
    'hex color'       => '/^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$/',
    'strong password' => '/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[\W_]).{8,}$/',
];

$tests = [
    'digits only'  => '12345',
    'alphanumeric' => 'Hello123',
    'hex color'    => '#FF5733',
];

foreach ($tests as $name => $value) {
    $result = preg_match($patterns[$name], $value) ? "PASS" : "FAIL";
    echo "$name ('$value'): $result\n";
}

// Modifiers:
// i — case insensitive
// m — multiline (^ and $ match line start/end)
// s — dotall (. matches newline too)
// x — extended (allow whitespace and comments)
// u — unicode

// Multiline example
$text = "Line 1\nLine 2\nLine 3";
preg_match_all('/^Line \d+$/m', $text, $matches);
print_r($matches[0]); // [Line 1, Line 2, Line 3]
?>

Previous Next

Ready to Level Up Your Skills?

Explore 500+ free tutorials across 20+ languages and frameworks.