0
0
PhpHow-ToBeginner · 3 min read

How to Use preg_match_all in PHP: Syntax and Examples

Use preg_match_all in PHP to find all matches of a regular expression pattern in a string. It returns the number of matches found and fills an array with all matched results. The function signature is preg_match_all(string $pattern, string $subject, array &$matches).
📐

Syntax

The preg_match_all function searches a string for all matches of a regular expression pattern. It takes three main parameters:

  • $pattern: The regular expression pattern to search for, enclosed in delimiters like /pattern/.
  • $subject: The string to search within.
  • &$matches: A variable passed by reference that will hold all matches found.

The function returns the number of matches found or 0 if none are found.

php
int preg_match_all(string $pattern, string $subject, array &$matches)
💻

Example

This example finds all words starting with the letter 'a' in a sentence and prints them.

php
<?php
$subject = "An apple a day keeps the doctor away.";
$pattern = '/\ba\w*/i'; // \b means word boundary, i means case-insensitive

if (preg_match_all($pattern, $subject, $matches)) {
    echo "Found matches:\n";
    print_r($matches[0]);
} else {
    echo "No matches found.";
}
?>
Output
Found matches: Array ( [0] => An [1] => apple [2] => a [3] => away )
⚠️

Common Pitfalls

Common mistakes when using preg_match_all include:

  • Forgetting to pass the $matches array by reference, which is required to store results.
  • Using incorrect delimiters or forgetting to escape special characters in the pattern.
  • Confusing preg_match (which finds only the first match) with preg_match_all (which finds all matches).
php
<?php
// Wrong: missing & before $matches, so $matches stays empty
$pattern = '/\d+/';
$subject = '123 456 789';
$matches = [];
preg_match_all($pattern, $subject, $matches); // $matches will be filled correctly

// Right: pass $matches by reference
preg_match_all($pattern, $subject, $matches);
print_r($matches[0]);
?>
Output
Array ( [0] => 123 [1] => 456 [2] => 789 )
📊

Quick Reference

ParameterDescription
$patternRegular expression pattern with delimiters
$subjectInput string to search
&$matchesArray to store all matches found
Return valueNumber of matches found or 0 if none

Key Takeaways

Use preg_match_all to find all matches of a regex pattern in a string.
Always pass the matches array by reference to collect results.
Remember preg_match_all returns the count of matches found.
Use proper regex delimiters and escape special characters.
preg_match_all differs from preg_match by returning all matches, not just the first.