How to Use preg_match in PHP for Regular Expressions
Regular expressions are powerful tools for pattern matching and data
validation in web development. This article provides a practical guide
on how to use PHP’s preg_match() function to search strings
for specific patterns. You will learn the basic syntax, how to perform
simple boolean matches, and how to extract specific parts of a string
using capturing groups.
Understanding the Syntax of preg_match()
The preg_match() function searches a subject string for
a match to a regular expression pattern. The basic syntax is as
follows:
preg_match(string $pattern, string $subject, array &$matches = null): int|false$pattern: The regular expression search pattern, enclosed in delimiters (typically slashes, like/pattern/).$subject: The input string you want to search.$matches: An optional array that gets populated with the search results if a match is found.
The function returns 1 if a match is found,
0 if no match is found, and false if an error
occurs.
Performing a Simple Match
To check if a specific pattern exists within a string, you can use
preg_match() inside an conditional statement.
$pattern = '/cat/i'; // The 'i' modifier makes the search case-insensitive
$string = 'The quick brown cat jumps over the lazy dog.';
if (preg_match($pattern, $string)) {
echo "Match found!";
} else {
echo "No match found.";
}In this example, the pattern /cat/i searches for the
word “cat” regardless of capitalization. Since “cat” is in the string,
the function returns 1, and the success message is
printed.
Capturing Specific Data Using Groups
If you need to extract specific parts of the matched text, you can
pass a third argument—an array variable—to preg_match().
Inside your pattern, use parentheses () to define capturing
groups.
$pattern = '/(\d{4})-(\d{2})-(\d{2})/'; // Matches YYYY-MM-DD date format
$string = 'The release date is 2023-10-25.';
if (preg_match($pattern, $string, $matches)) {
echo "Full match: " . $matches[0] . "\n"; // Output: 2023-10-25
echo "Year: " . $matches[1] . "\n"; // Output: 2023
echo "Month: " . $matches[2] . "\n"; // Output: 10
echo "Day: " . $matches[3] . "\n"; // Output: 25
}When a match is found: - $matches[0] contains the entire
text that matched the pattern. - $matches[1] contains the
text matched by the first parenthesized subpattern. -
$matches[2] and subsequent keys contain data from
subsequent capturing groups.
Common Regex Modifiers
Modifiers are appended after the closing pattern delimiter to alter
the search behavior: - i: Case-insensitive
search. - m: Multi-line search, changing
how caret (^) and dollar ($) anchors behave. -
s: Allows the dot (.)
metacharacter to match all characters, including newlines.