SyntaxStudy
Sign Up
PHP preg_match() in PHP
PHP Intermediate 4 min read

preg_match() in PHP

preg_match()

preg_match() tests if a pattern matches a string and captures groups. It returns 1 on match, 0 on no match, and false on error.

Example
<?php
// Test if string matches
if (preg_match("/^\d{5}$/", $zipCode)) {
    echo "Valid zip";
}

// Capture groups
$pattern = "/^(\d{4})-(\d{2})-(\d{2})$/";
if (preg_match($pattern, "2024-06-15", $matches)) {
    echo $matches[0]; // "2024-06-15" (full match)
    echo $matches[1]; // "2024" (group 1)
    echo $matches[2]; // "06"
    echo $matches[3]; // "15"
}
Pro Tip

Delimit PHP regex patterns with / and always test with === 1 for strict match checking (not just truthy).