PHP
All matches with preg_match_all()
Learn to get all matches in a string with preg_match_all().
All matches with preg_match_all
preg_match finds only the first match. To get every match, use preg_match_all($pattern, $subject, $matches).
The return value is the total match count (0, 1, 2, ...). Matches are stored in $matches using the default PREG_PATTERN_ORDER layout: $matches[0] is an array of all full matches.
So to loop over every hashtag or every number, the foreach ($matches[0] as $m) idiom is common.
PREG_PATTERN_ORDER and PREG_SET_ORDER
The fourth parameter of preg_match_all controls how matches are arranged. Two common options exist:
PREG_PATTERN_ORDER (default): $matches[0] is the list of all full matches, $matches[1] is all matches of the first group. Groups are arranged as columns.
PREG_SET_ORDER: $matches[0] is all groups of the first match, $matches[1] is all groups of the second match. Each match is its own row.
Exercise Find every hashtag
Find every #tag in $post = "Today #php and #regex"; using preg_match_all. Put the pattern into $pattern, call with $matches, and print each tag on a new line with foreach.
Show example solution
Set pattern to "/#\w+/". Call preg_match_all($pattern, $post, $matches). Print with foreach ($matches[0] as $tag) { echo $tag . "\n"; }
Example solution:
<?php
// Find every hashtag (#...) with preg_match_all
$post = "Today #php and #regex";
// Add pattern, matches and the call
$pattern = "/#\w+/";
preg_match_all($pattern, $post, $matches);
// Print each tag on a new line
foreach ($matches[0] as $tag) {
echo $tag . "\n";
}
Test yourself
-
What does preg_match_all return?
- The total match count
- The first matched text
- true or false
- The array of matches
Show answer
The total match count — Correct. The return value is the match count; the matches themselves go into $matches.
-
Loop over the matches
foreach (____ as $tag) {
echo $tag . "\n";
}
Show answer
foreach ($matches[0] as $tag) {
echo $tag . "\n";
}
-
Constants and their meanings
- PREG_PATTERN_ORDER
- Arranges groups as columns
- PREG_SET_ORDER
- Arranges matches as rows
- $matches[0]
- List of all matches
- preg_match_all
- Function that finds all matches
Next lesson: Character classes