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.
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.
<?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"
}
Delimit PHP regex patterns with / and always test with === 1 for strict match checking (not just truthy).