PHP preg_match() Function
preg_match() searches a string for a match to a regular expression. It returns 1 when a match is found, 0 when no match is found, and false when an error occurs.
Basic Example
$email = "person@example.com";
if (preg_match('/^[^\s@]+@[^\s@]+\.[^\s@]+$/', $email) === 1) {
echo "Pattern matched";
}
This example demonstrates matching only; it is not a complete email validation standard. For common email format validation, consider filter_var().
Capture Groups
Use parentheses to capture parts of a match.
if (preg_match('/^(\d{4})-(\d{2})-(\d{2})$/', $date, $matches) === 1) {
$year = $matches[1];
$month = $matches[2];
$day = $matches[3];
}
A successful pattern match still needs semantic validation. For example, a month value of 19 matches two digits but is not a valid month.
Avoid Unsafe Dynamic Patterns
If user input must be included in a pattern, quote it with preg_quote() where appropriate. Keep patterns bounded and avoid catastrophic backtracking from poorly designed expressions.
Summary
preg_match() is useful for pattern matching and extraction. Check its return values carefully and validate the meaning of captured data separately.