How to Use preg_match in PHP: Syntax and Examples
Use
preg_match in PHP to check if a string matches a pattern defined by a regular expression. It returns 1 if the pattern matches, 0 if not, and false on error. The basic syntax is preg_match('/pattern/', $string, $matches) where $matches stores the found results.Syntax
The preg_match function checks if a string matches a regular expression pattern.
pattern: The regular expression enclosed in delimiters, usually slashes/pattern/.subject: The string you want to test.matches(optional): An array to store the matched parts.flagsandoffset(optional): Advanced options for matching behavior.
php
int preg_match(string $pattern, string $subject, array &$matches = null, int $flags = 0, int $offset = 0);
Example
This example checks if the string contains the word "cat" and prints the matched word.
php
<?php $pattern = '/cat/'; $text = 'The cat is sleeping.'; if (preg_match($pattern, $text, $matches)) { echo "Match found: " . $matches[0]; } else { echo "No match found."; } ?>
Output
Match found: cat
Common Pitfalls
Common mistakes when using preg_match include:
- Forgetting delimiters around the pattern (e.g., using
catinstead of/cat/). - Not escaping special characters in the pattern.
- Assuming
preg_matchreturns the matched string instead of 1 or 0. - Not checking the return value before using the
$matchesarray.
php
<?php // Wrong: missing delimiters // preg_match('cat', 'cat', $matches); // This causes a warning // Right: with delimiters preg_match('/cat/', 'cat', $matches); echo $matches[0]; // Outputs: cat ?>
Output
cat
Quick Reference
| Usage | Description |
|---|---|
| preg_match('/pattern/', $string) | Returns 1 if pattern matches, 0 if not |
| preg_match('/pattern/', $string, $matches) | Stores matched parts in $matches array |
| Use delimiters like / or # | Required around the regex pattern |
| Escape special chars with \\ | To match characters like . * + ? etc. |
| Check return value before using $matches | Avoid errors if no match found |
Key Takeaways
Always enclose your regex pattern in delimiters like slashes (/pattern/).
preg_match returns 1 if a match is found, 0 if not, and false on error.
Use the optional $matches array to get the matched text from the string.
Escape special regex characters to match them literally.
Check the return value before accessing $matches to avoid errors.