PHP Reference ยท Regular Expressions
PHP preg_match_all() function
Reference for PHP preg_match_all(): find every match of a regular expression, choose PREG_PATTERN_ORDER or PREG_SET_ORDER, named groups, offsets and counts.
The preg_match_all() function finds every non-overlapping match of a regular expression in a string. It returns the number of matches and, if you pass a variable, fills it with the results.
The shape of the results is the part people forget: by default the array is grouped by capture group (all full matches, then all first groups, ...). Pass PREG_SET_ORDER to get one entry per match instead.
<?php $count = preg_match_all('/\d+/', 'a1 b22 c333', $m); echo $count; // 3 print_r($m[0]); // ['1', '22', '333']
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_all( string $pattern, string $subject, array &$matches = null, int $flags = 0, int $offset = 0 ): int|false
| Name | Description |
|---|---|
$pattern |
The regular expression with delimiters. |
$subject |
The string to search. |
$matches |
Receives the results. With PREG_PATTERN_ORDER (default): $matches[0] is the list of full matches, $matches[1] the list of group 1, and so on. |
$flags |
PREG_PATTERN_ORDER, PREG_SET_ORDER, PREG_OFFSET_CAPTURE, PREG_UNMATCHED_AS_NULL. Orders cannot be combined with each other. |
$offset |
Byte position at which to start. |
Return value: the number of full matches (possibly 0), or false on error.
Errors / Exceptions: an invalid pattern emits a warning and returns false.
Usage notes
- Default is pattern order.
$m[1]holds all values of group 1. UsePREG_SET_ORDERwhen you want to loop over matches and read each match's groups together. - No match: the function returns
0and$matchesbecomes an array of empty arrays (one per group). - Matches never overlap. After a match, the search continues from its end. For overlapping results use a lookahead such as
(?=(\d\d)). - Empty matches count. A pattern that can match nothing, like
a*, matches at positions where there are noas, so the count can exceed what you expect. - Greedy vs. lazy.
<.+>swallows from the first<to the last>; use<.+?>or<[^>]+>. - Named groups appear under both their name and their index.
- Memory. All matches are collected at once; for huge inputs consider iterating with
preg_match()and an offset, orpreg_replace_callback(). - Counting only: you may omit
$matchesif you just want the count. - Parsing HTML or JSON is better done with a real parser than with regular expressions.