preg_match_all
Finds every match of a regular expression.
Syntax
preg_match_all(string $pattern, string $subject, array &$matches = null): int|falseParameters
| Parameter | Type | Description |
|---|---|---|
| $pattern | string | The pattern between delimiters. |
| $subject | string | The string to search in. |
| $matches | array | Optional. Receives all the matches. |
Return value
int|falseThe number of matches, or `false` on an error.
Examples
Every number in a text:
<?php
$count = preg_match_all('/\d+/', 'Order 15, items 3, total 4200', $matches);
echo $count, ': ', implode(', ', $matches[0]);Output:
3: 15, 3, 4200Every hashtag:
<?php
preg_match_all('/#(\w+)/', 'Learning #php and #sql', $matches);
echo implode(', ', $matches[1]);Output:
php, sqlNotes
$matches[0] holds the full matches, $matches[1] the values of the first group, and so on.
See also
- preg_match — Tests a string against a regular expression.
- preg_split — Splits a string by a regular expression.
Related recipes
In the tutorial
- Regular expressions — Regular expressions in PHP — preg_match, preg_replace, preg_split, groups and the basic pattern notation.