preg_match_all()

preg_match_all() — Perform a global regular expression match.

Built-in function of PHP 8.5. The manual lists it as available in PHP 4, PHP 5, PHP 7, PHP 8. This page is the reference card: signature, parameters and return value, plus the changelog and the example the manual provides.

What it does

Searches subject for all matches to the regular expression given in pattern and puts them in matches in the order specified by flags.

Signature

preg_match_all(string $pattern, string $subject, array &$matches = null, int $flags = 0, int $offset = 0): int|false

Parameters

ParameterTypeWhat it takes
$patternstringThe pattern to search for, as a string.
$subjectstringThe input string.
&$matchesarrayArray of all matches in multi-dimensional array ordered according to flags.
$flagsintCan be a combination of the following flags (note that it doesn't make sense to use PREG_PATTERN_ORDER together with PREG_SET_ORDER): PREG_PATTERN_ORDER Orders results so that $matches[0] is an array of full pattern matches, $matches[1] is an array of strings matched by the first parenthesized subpattern, and so on. <?php preg_match_all("|<[^>]+>(.*)</[^>]+>|U", "<b>example: </b><div align=left>this is a ...
$offsetintNormally, the search starts from the beginning of the subject string. The optional parameter offset can be used to specify the alternate place from which to start the search (in bytes).

Return value

Returns the number of full pattern matches (which might be zero), or false on failure.

Example

A runnable snippet:

preg_match_all("/\(? (\d{3})? \)? (?(1) [\-\s] ) \d{3}-\d{4}/x", "Call 555-1212 or 1-800-555-1212", $phones);

Changelog

VersionChange
7.2.0The PREG_UNMATCHED_AS_NULL is now supported for the flags parameter.

See also

preg_quote(), preg_match(), preg_replace(), preg_split(), preg_last_error()

All PHP 8.5 built-in functions

Reference card built from the PHP manual page preg_match_all() (PHP documentation, CC BY 3.0). The page is generated from the manual, so the wording of the parameter and return value text follows php.net.