0
0
PHPprogramming~5 mins

Preg_match_all for global matching in PHP

Choose your learning style9 modes available
Introduction

Preg_match_all helps find all parts of a text that match a pattern, not just the first one.

You want to find every email address in a long text.
You need to get all words that start with a capital letter.
You want to extract all numbers from a sentence.
You want to find all hashtags in a social media post.
Syntax
PHP
int preg_match_all(string $pattern, string $subject, array &$matches, int $flags = PREG_PATTERN_ORDER, int $offset = 0)

$pattern is the pattern you want to find.

$matches will hold all found results after running the function.

Examples
This finds all words starting with 'a' in the text.
PHP
$text = "apple banana cherry";
preg_match_all('/a\w+/', $text, $matches);
print_r($matches);
This finds all groups of digits in the text.
PHP
$text = "123 abc 456 def";
preg_match_all('/\d+/', $text, $matches);
print_r($matches);
Sample Program

This program finds all email addresses in the given text and prints them.

PHP
<?php
$text = "Contact us at info@example.com or support@example.org.";
preg_match_all('/[\w.-]+@[\w.-]+\.\w+/', $text, $matches);
print_r($matches[0]);
?>
OutputSuccess
Important Notes

preg_match_all returns the number of matches found.

The matches are stored in $matches as arrays, with full matches in $matches[0].

Summary

Use preg_match_all to find all matches of a pattern in a string.

The results are stored in an array you provide.

This is useful when you want every match, not just the first one.