PHP preg_match_all() Function

PHP preg_last_error() Function
PHP preg_match() Function

In this article, you will learn how to get the count of matches of a pattern in PHP string. The preg_match_all() function in PHP returns the number of matches of a pattern that were found in a string and populates a variable with the matches that were found.

what is the syntax of the PREG_MATCH_ALL function in php?

preg_match_all(pattern, input, matches, flags, offset)
ParameterDescription
patternRequired. Contains a regular expression indicating what to search for
inputRequired. The string in which the search will be performed
matchesOptional. The variable used in this parameter will be populated with an array containing all of the matches that were found
flagsOptional. A set of options that change how the matches array is structured.

One of the following structures may be selected:
PREG_PATTERN_ORDER – Default. Each element in the matches array is an array of matches from the same grouping in the regular expression, with index 0 corresponding to matches of the whole expression and the remaining indices for subpattern matches.PREG_SET_ORDER – Each element in the matches array contains matches of all groupings for one of the found matches in the string.Any number of the following options may be applied:PREG_OFFSET_CAPTURE – When this option is enabled, each match, instead of being a string, will be an array where the first element is a substring containing the match and the second element is the position of the first character of the substring in the input.PREG_UNMATCHED_AS_NULL – When this option is enabled, unmatched subpatterns will be returned as NULL instead of as an empty string.
offsetOptional. 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
PHP PREG_MATCH_ALL() method

examples of the PREG_MATCH_ALL function

Example 1. In this example, we 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);
}
?>
PHP preg_last_error() Function
PHP preg_match() Function
en English
X
Scroll to Top