Definition and Usage
- PHP Version
- 4+
The preg_match_all() function uses a regular expression to find all matching parts of a given string and returns the result.
Features
- This function is case-sensitive.
- It finds all substrings that match a regular expression pattern and returns the number of matches as an integer. If no matches are found, it returns
0. - All matched substrings can also be stored in an array, where each match is stored as a separate element. To do this, specify a variable to be assigned to a parameter.
- It is useful for checking strings against specific patterns, such as email addresses, URLs, and HTML tags.
Basic Example
/* Finds all substrings that match
regular expression patterns in a string
and returns the count as an integer. */
// The given string
$str = 'apple orange banana apple';
// The regular expression pattern to search for
$pattern = '/apple/';
// Apply the function and return the result
$result = preg_match_all($pattern, $str);
var_dump($result); // Output: int(2)
/* All matched substrings can also be stored
in an array composed of separate elements.
Specify a variable to assign to the third parameter. */
// Specify a variable ($matches) to assign to the third parameter
$result = preg_match_all($pattern, $str, $matches);
// Check the assigned array
print_r($matches);
/* Output:
Array
(
[0] => Array
(
[0] => apple
[1] => apple
)
)
*/
To find a specific pattern in a string using a regular expression and replace it with another string, use the preg_replace() function.
Syntax
preg_match_all(
string $pattern,
string $subject,
array &$matches = null,
int $flags = 0,
int $offset = 0
): int|false
/* preg_match_all(
pattern,
the string to be searched[,
an array to store the matched parts[,
flags that specify additional options[,
the offset within the string where the search starts]]]
);
*/
Parameters
$pattern |
Required. The regular expression pattern to search for. |
|---|---|
$subject |
Required. The string to be searched. |
&$matches |
Optional. An array to store the results that match the regular expression pattern.
This array is filled after the function call. (It is a reference variable.)
|
$flags |
Optional. Flags that specify how the matching results array is ordered.
If this value is omitted, the default value 0 is used, and PREG_PATTERN_ORDER is applied by default.
The following flags can be used in combination:
|
$offset |
Optional. The offset within the string where the search starts. It starts from 0.
When this value is specified, the regular expression search is performed starting from the specified index (in bytes) of the string. |
Please note!
In other languages (for example, JavaScript), a g (global) flag is required to find all matches of a pattern (for example, the JavaScript string match() function).
However, PCRE functions related to regular expressions in PHP (for example, preg_match() and preg_match_all()) do not use the g flag.
Changelog
| Version | Description |
|---|---|
| 7.2.0 | It is now possible to use the PREG_UNMATCHED_AS_NULL flag as a value for the $flags parameter. |
Return Values
- Finds all substrings that match the regular expression pattern and returns the count as an integer.
- If no matching pattern is found, it returns
0. - An array containing the matched items is assigned to the variable passed to the function as a parameter.
- If an error occurs, it returns
false. If the provided regular expression pattern is invalid, anE_ERRORis emitted.
Results That Match the Regular Expression Pattern and Return Value Examples
Returning the Total Number of Matches
The preg_match_all() function searches the subject string for all matching substrings.
Its return value is the total number of matches found.
$pattern = '/apple/';
$subject = "apple orange banana apple";
$result = preg_match_all($pattern, $subject);
if ($result !== false) {
var_dump($result); // Output: int(2)
}
In contrast, the similar preg_match() function stops searching as soon as it finds the first matching pattern in the string and returns 1.
Returning 0 When No Matching Pattern Is Found
If no matching pattern is found, the function returns 0. An important point to note here is that it does not return false in this case. The value false is returned only when an error occurs.
$pattern = '/grape/';
$subject = "apple orange banana apple";
$result = preg_match_all($pattern, $subject);
if ($result !== false) {
var_dump($result); // Output: int(0)
}
Returning false When an Error Occurs
error_reporting(0); // Disable error output
$pattern = '/apple'; // Invalid regular expression
$subject = "apple orange banana apple";
$result = preg_match_all($pattern, $subject);
if ($result !== false) {
var_dump($result);
} else {
echo 'An error occurred.';
}
// Output: 'An error occurred.'
Assigning Matched Items to a Variable Passed as a Parameter
To assign the matched items to another variable when using preg_match_all(),
you must pass an array by reference as the third parameter.
Let's look at an example.
// Find numbers in the given string
$string = 'This is a sample text containing 123 and 456.';
// Pattern: match numbers
$pattern = '/\d+/';
// Declare an empty array to store the matches
$matches = array();
// Pass $matches as a parameter
$num_of_matches = preg_match_all($pattern, $string, $matches);
// Output the result
if ($num_of_matches > 0) {
var_dump($matches);
// array(1) {
// [0]=> array(2) {
// [0]=> string(3) "123"
// [1]=> string(3) "456"
// }
// }
}
Here, the $matches array is passed as the third parameter to the preg_match_all() function. After the function call, the $matches array is populated with the matched substrings.
By doing this, the matched items are assigned to the $matches array,
and the values can be accessed and used outside the function scope as well.
Examples of Return Values and $flags When the Regular Expression Includes Capture Groups
The preg_match_all() function does more than simply find all matches and return a value. Depending on the value specified for the $flags parameter and whether the regular expression includes capture groups, the structure of the result array can vary significantly.
elow are examples showing how the result array differs based on the value of $flags when the specified regular expression contains capture groups.
PREG_PATTERN_ORDER
The matching results are organized by pattern (capture group).
- The matching results are organized by pattern (capture group).
$matches[1],$matches[2], … contain arrays of substrings that match each parenthesized group- If the pattern does not include any capture groups, indices other than
$matches[0]do not exist
// Example string
$string = "apple orange banana apple";
// Regular expression pattern:
// Find 'apple' or 'orange' and wrap it in a parenthesized group
$pattern = '/(apple|orange)/';
// Using PREG_PATTERN_ORDER
// - Organizes the matching results by pattern (capture group)
// - $matches : the array variable to which the results are assigned
// - $matches[0] : substrings that match the entire pattern
// - $matches[1] : substrings that match the first parenthesized group
preg_match_all($pattern, $string, $matches, PREG_PATTERN_ORDER);
// Output the result
print_r($matches);
/*
Output:
Array
(
[0] => Array ( [0] => apple [1] => orange [2] => apple )
[1] => Array ( [0] => apple [1] => orange [2] => apple )
)
*/
PREG_SET_ORDER
The matching results are grouped by individual match.
- For each match,
$matches[n][0]contains the substring that matches the entire pattern - If capture groups exist,
$matches[n][1],$matches[n][2], … contain the substrings matched by each group - If there are no capture groups, indices such as
$matches[n][1],$matches[n][2], … do not exist - his flag cannot be used together with
PREG_PATTERN_ORDER
// Example string
$string = "apple orange banana apple";
// Regular expression pattern:
// Match 'apple' or 'orange' and wrap it in a capture group
$pattern = '/(apple|orange)/';
// Use PREG_SET_ORDER
// - Groups results by individual match
// - $matches : the array variable to which the results are assigned
// - $matches[0], $matches[1], ... : each represents one match
preg_match_all($pattern, $string, $matches, PREG_SET_ORDER);
// Output the result
print_r($matches);
/*
Output:
Array
(
[0] => Array ( [0] => apple [1] => apple ) // First match: entire match + first group
[1] => Array ( [0] => orange [1] => orange ) // Second match: entire match + first group
[2] => Array ( [0] => apple [1] => apple ) // Third match: entire match + first group
)
*/
PREG_OFFSET_CAPTURE
Stores the starting position (offset) of each match along with the matched string.
- Each element in
$matchesis an array in the form[matched string, starting offset] - If capture groups exist, the same structure is applied to each group as well
// Example string
$string = "apple orange banana apple";
// Regular expression pattern:
// Match 'apple' or 'orange' and wrap it in a capture group
$pattern = '/(apple|orange)/';
// Use PREG_OFFSET_CAPTURE
// - Stores the starting offset along with each matched string
// - $matches : the array variable to which the results are assigned
// - Each element is in the form [matched string, starting offset]
preg_match_all($pattern, $string, $matches, PREG_OFFSET_CAPTURE);
// Output the result
print_r($matches);
/*
Output:
Array
(
[0] => Array (
[0] => Array("apple", 0) // First full match and its offset
[1] => Array("orange", 6) // Second full match and its offset
[2] => Array("apple", 19) // Third full match and its offset
)
[1] => Array (
[0] => Array("apple", 0) // First group match and its offset
[1] => Array("orange", 6) // Second group match and its offset
[2] => Array("apple", 19) // Third group match and its offset
)
)
*/
PREG_UNMATCHED_AS_NULL
Treats unmatched subpatterns as null. If this flag is not used, unmatched subpatterns are represented as empty strings ('').
- This flag has no effect when the pattern does not contain capture groups
// Example string
$string = "apple banana";
// Regular expression pattern:
// Three groups: 'apple', 'banana', 'orange'
$pattern = '/(apple)|(banana)|(orange)/';
// Use PREG_UNMATCHED_AS_NULL
// - Treats unmatched subpatterns as null
// - $matches : the array variable to which the results are assigned
// - Each group match is stored as either a string or null
preg_match_all(
$pattern,
$string,
$matches,
PREG_PATTERN_ORDER | PREG_UNMATCHED_AS_NULL
);
// Output the result
print_r($matches);
/*
Output:
Array
(
[0] => Array ( [0] => apple [1] => banana ) // Full pattern matches
[1] => Array ( [0] => apple [1] => null ) // First group: only 'apple' matched
[2] => Array ( [0] => null [1] => banana ) // Second group: only 'banana' matched
[3] => Array ( [0] => null [1] => null ) // Third group: no match → null
)
*/
Practical Examples
The preg_match_all() function is useful for checking strings against specific patterns such as email addresses and URLs. It can also be applied effectively in a variety of other situations. Below are several practical examples.
Validating Email Addresses
$string = 'For inquiries, please contact help@example.com or support@example.org.';
$pattern = '/\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b/';
$matches = array();
$result = preg_match_all($pattern, $string, $matches);
if ($result !== false && $result > 0) {
print_r($matches[0]); // Output all matched email addresses
echo "\nFirst email: " . $matches[0][0]; // Output only the first email address
} else {
echo 'No valid email address format was found.';
}
// Output:
// Array ( [0] => help@example.com [1] => support@example.org )
// First email: help@example.com
Validating URLs
$string = 'For more information, visit https://www.example.com.';
$pattern = '/\b(?:https?:\/\/)?(?:www\.)?[a-zA-Z0-9-]+(?:\.[a-z]{2,})+(?:\/[^\s]*)?\b/';
$matches = array();
$result = preg_match_all($pattern, $string, $matches);
if ($result !== false && $result > 0) {
echo $matches[0][0]; // Output the first matched URL
} else {
echo 'No valid URL format was found.';
}
// Output: https://www.example.com
Extracting Tags from HTML
$html = '<div class="container"><p>Hello, <b>world!</b></p></div>';
$tagPattern = '/<[^>]+>/'; // Regular expression to find HTML tags
$matches = array();
$result = preg_match_all($tagPattern, $html, $matches);
if ($result !== false && $result > 0) {
print_r($matches[0]); // Output all matched tags
} else {
echo 'No tags were found.';
}
// Output:
// Array ( [0] => <div class="container"> [1] => <p> [2] => <b> [3] => </b> [4] => </p> [5] => </div> )
Extracting CSS Class Selectors
$css = '.header { color: #333; } .main-content { font-size: 16px; }';
$classPattern = '/\.([a-zA-Z0-9_-]+)/'; // Pattern for CSS class selectors
$matches = array();
$result = preg_match_all($classPattern, $css, $matches);
if ($result !== false && $result > 0) {
print_r($matches[0]); // Output all matched class selectors
} else {
echo 'No CSS class selectors were found.';
}
// Output:
// Array ( [0] => .header [1] => .main-content )
References
See also
- PHP preg_match() Function – Check if a String Matches a Regular Expression
- PHP preg_replace() Function – Replace Text Using Regular Expressions
- PHP preg_split() Function – Splitting a String into an Array Using Regular Expressions
- PHP str_replace() Function – Replace Text in a String
- PHP substr() Function – Slice Strings by Position and Length
- PHP mb_substr() Function – Multibyte-Safe Alternative to substr()