Understanding PHP preg_match_all: Syntax, Parameters, and Examples
This article explains PHP's preg_match_all function, detailing its purpose, parameters, return values, and providing multiple code examples that demonstrate how to extract phone numbers, capture HTML tags, and use named subpatterns with regular expressions.
PHP's preg_match_all() function performs a global regular expression match, searching a subject string for all occurrences of a pattern and storing the results in an array.
Parameters
pattern : the regular expression pattern as a string.
subject : the input string to search.
matches : an output array that receives the matches, ordered according to the flags.
flags : optional flags such as PREG_PATTERN_ORDER or PREG_SET_ORDER (cannot be combined).
offset : optional byte offset to start the search.
Return value
The function returns the number of full pattern matches (or FALSE on error).
Examples
Example 1 – extracting phone numbers:
<?php
preg_match_all("/\(? (\d{3})? \)? (?(1) [\-\s] ) \d{3}-\d{4}/x",
"Call 555-1212 or 1-800-555-1212",
$phones);
?>Example 2 – capturing HTML tags with PREG_SET_ORDER:
<?php
$html = "<b>bold text</b><a href=howdy.html>click me</a>";
preg_match_all("/(<([\w]+)[^>]*>)(.*?)(<\/\\2>)/", $html, $matches, PREG_SET_ORDER);
foreach ($matches as $val) {
echo "matched: " . $val[0] . "
";
echo "part 1: " . $val[1] . "
";
echo "part 2: " . $val[2] . "
";
echo "part 3: " . $val[3] . "
";
echo "part 4: " . $val[4] . "
";
}
?>Example 3 – named subpatterns:
<?php
$str = <<<FOO
a: 1
b: 2
c: 3
FOO;
preg_match_all('/(?P<name>\w+): (?P<digit>\d+)/', $str, $matches);
print_r($matches);
?>Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Laravel Tech Community
Specializing in Laravel development, we continuously publish fresh content and grow alongside the elegant, stable Laravel framework.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
