preg_match
Tests a string against a regular expression.
Syntax
preg_match(string $pattern, string $subject, array &$matches = null): int|falseParameters
| Parameter | Type | Description |
|---|---|---|
| $pattern | string | The pattern between delimiters, for example `/\d+/`. |
| $subject | string | The string to test. |
| $matches | array | Optional. Receives the match and its groups. |
Return value
int|false`1` if the pattern is found, `0` if not, `false` on a pattern error.
Examples
Checking a date format:
<?php
echo preg_match('/^\d{4}-\d{2}-\d{2}$/', '2025-01-30'), "\n";
echo preg_match('/^\d{4}-\d{2}-\d{2}$/', '30.01.2025');Output:
1
0Groups go into the array:
<?php
preg_match('/(\w+)@(\w+\.\w+)/', 'Write to anna@example.com', $matches);
echo $matches[1], ' | ', $matches[2];Output:
anna | example.comNotes
For non-ASCII text add the u modifier: /кот/u. The function finds only the first match — preg_match_all() finds them all.
See also
- preg_replace — Replaces everything that matches a regular expression.
- preg_match_all — Finds every match of a regular expression.
- str_contains — Checks whether a string contains a given substring.
Related recipes
In the tutorial
- Regular expressions — Regular expressions in PHP — preg_match, preg_replace, preg_split, groups and the basic pattern notation.