Encodera

Thanks for reading!

Donate to the site — we work hard for you.

PHP reference

preg_match_all

Finds every match of a regular expression.

Syntax

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

Parameters

ParameterTypeDescription
$patternstringThe pattern between delimiters.
$subjectstringThe string to search in.
$matchesarrayOptional. 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, 4200

Every hashtag:

<?php
 
preg_match_all('/#(\w+)/', 'Learning #php and #sql', $matches);
 
echo implode(', ', $matches[1]);

Output:

php, sql

Notes

$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.

Thanks for reading!

Donate to the site — we work hard for you.