PHP preg_match_all() Function
Example
Find all occurrences of "ain" in a string:
<?php
$str = "The rain in SPAIN falls mainly on the plains.";
$pattern =
"/ain/i";
if(preg_match_all($pattern, $str, $matches)) {
print_r($matches);
}
?>
Try it Yourself »
Definition and Usage
The preg_match_all()
function returns the number of matches of a pattern that were found
in a string and populates a variable with the matches that were found.
Syntax
preg_match_all(pattern, input, matches, flags, offset)
Parameter Values
Parameter | Description |
---|---|
pattern | Required. Contains a regular expression indicating what to search for |
input | Required. The string in which the search will be performed |
matches | Optional. The variable used in this parameter will be populated with an array containing all of the matches that were found |
flags | Optional. A set of options that change how the matches array is structured. One of the following structures may be selected:
|
offset | Optional. Defaults to 0. Indicates how far into the string to begin searching. The preg_match() function will not find matches that occur before the position given in this parameter |
Technical Details
Return Value: | Returns the number of matches found or false if an error occurred |
---|---|
PHP Version: | 4+ |
Changelog: | PHP 7.2 - Added the PREG_UNMATCHED_AS_NULL flag PHP 5.4 - The matches parameter became optional PHP 5.3.6 - The function returns false when the offset is longer than the length of the input PHP 5.2.2 - Named subpatterns can use the (?'name') and (? <name>) syntax in addition to the previous (?P<name>) |
More Examples
Example
Use PREG_PATTERN_ORDER to set the structure of the matches array. In this example, each element in the matches array has all of the matches for one of the groupings of the regular expression.
<?php
$str = "abc ABC";
$pattern = "/((a)b)(c)/i";
if(preg_match_all($pattern,
$str, $matches, PREG_PATTERN_ORDER)) {
print_r($matches);
}
?>
Try it Yourself »
❮ PHP RegExp Reference
Copyright 1999-2023 by Refsnes Data. All Rights Reserved.