PHP Reference Β· Regular Expressions
PHP preg_match() function
Reference for PHP preg_match(): test a string against a regular expression, capture groups and named groups, flags, offsets and the int|false return value.
The preg_match() function searches a string for the first match of a regular expression. It returns 1 if the pattern matched, 0 if not, and false if an error occurred. Optionally it fills an array with the matched text and the text of each capture group.
Use it to validate input, to pull one piece of data out of a string, or to test a condition. To find every match, use preg_match_all().
<?php if (preg_match('/^\d{4}-\d{2}-\d{2}$/', '2025-03-09')) { echo "looks like a date"; }
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input Β· what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input Β· what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.
Syntax
preg_match( string $pattern, string $subject, array &$matches = null, int $flags = 0, int $offset = 0 ): int|false
| Name | Description |
|---|---|
$pattern |
The regular expression, with delimiters and optional modifiers, such as '/abc/i'. |
$subject |
The string to search. |
$matches |
Optional. Receives [0] the full match, then one entry per capture group; named groups appear under their name and their number. |
$flags |
PREG_OFFSET_CAPTURE stores [text, byte offset] pairs. PREG_UNMATCHED_AS_NULL uses null for groups that did not participate. |
$offset |
Byte position where the search starts. |
Return value: 1 for a match, 0 for no match, false on error (see preg_last_error()).
Errors / Exceptions: an invalid pattern emits a warning and returns false; no exception is thrown.
Usage notes
- Strict check.
0andfalseare different. If failures matter, test=== falseseparately from=== 1. - Stops at the first match.
$matcheshas data only for that one match. - Trailing groups that did not match are dropped from
$matches(the array is shorter), while unmatched groups in the middle become"".PREG_UNMATCHED_AS_NULLmakes the array complete. $matchesis overwritten on every call, and is an empty array when nothing matched.^with$offsetdoes not move:^still means the start of the subject. Use\Gto anchor at the offset.- Offsets are bytes, not characters, even with the
umodifier. - Unicode: add the
umodifier so.,\wand\p{...}work on UTF-8 characters. Invalid UTF-8 then returnsfalse. - Use
$carefully for validation.$also matches before a final newline; use\zor theDmodifier when that matters. - Simple checks don't need regex.
str_contains()andstr_starts_with()are faster and clearer. - Escape user text with
preg_quote()before putting it into a pattern.