Bird
Raised Fist0
PHPprogramming~10 mins

Preg_match_all for global matching in PHP - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Preg_match_all for global matching
Start with input string
↓
Apply preg_match_all with pattern
↓
Scan entire string for all matches
↓
Store all matches in array
↓
Return number of matches found
↓
Use matches as needed
↓
End
The function scans the whole string, finds all parts matching the pattern, stores them, and returns how many matches it found.
Execution Sample
PHP
<?php
$input = "apple banana apple cherry";
preg_match_all('/apple/', $input, $matches);
print_r($matches[0]);
?>
This code finds all occurrences of 'apple' in the input string and prints them.
Execution Table
StepActionPatternInput StringMatches FoundOutput
1Start with input stringapple banana apple cherry
2Call preg_match_all/apple/apple banana apple cherry
3Scan string from start/apple/apple banana apple cherryFound 'apple' at pos 0
4Continue scanning/apple/apple banana apple cherryFound 'apple' at pos 13
5No more matches/apple/apple banana apple cherryTotal matches: 2
6Store matches in array/apple/apple banana apple cherry['apple', 'apple']
7Print matches/apple/apple banana apple cherry['apple', 'apple']Array ( [0] => apple [1] => apple )
8End execution
💡 No more matches found in the string, preg_match_all returns total count 2.
Variable Tracker
VariableStartAfter Step 3After Step 4After Step 6Final
$input"apple banana apple cherry""apple banana apple cherry""apple banana apple cherry""apple banana apple cherry""apple banana apple cherry"
$matchesempty['apple']['apple', 'apple']['apple', 'apple']['apple', 'apple']
Key Moments - 3 Insights
Why does preg_match_all find multiple matches instead of stopping at the first?
Because preg_match_all scans the entire string for all matches, not just the first one, as shown in steps 3 and 4 where it finds two 'apple' matches.
What is stored inside the $matches array?
The $matches array stores all matched strings found by preg_match_all, as seen in step 6 where both 'apple' matches are stored.
Why is the output printed from $matches[0]?
Because preg_match_all stores the full matches in $matches[0], which is why printing $matches[0] shows all matched strings, as in step 7.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, how many matches does preg_match_all find?
A2
B1
C3
D0
💡 Hint
Check the 'Matches Found' column in steps 5 and 6.
At which step does preg_match_all store all matches in the array?
AStep 3
BStep 4
CStep 6
DStep 7
💡 Hint
Look for the step mentioning storing matches in the 'Matches Found' column.
If the input string had no 'apple', what would preg_match_all return?
AAn array with one empty string
BAn empty array and zero matches
CAn error
DThe whole input string
💡 Hint
Think about what happens when no matches are found, as explained in the exit note.
Concept Snapshot
preg_match_all(pattern, string, matches) scans the whole string
Finds all parts matching pattern
Stores matches in matches array
Returns number of matches found
Use matches[0] for full matched strings
Full Transcript
This example shows how preg_match_all works in PHP. It takes a pattern and a string, then finds all parts of the string that match the pattern. It stores these matches in an array and returns how many matches it found. The code example finds all 'apple' words in the string 'apple banana apple cherry' and prints them. The execution table traces each step: starting with the input, scanning for matches, storing them, and printing the results. The variable tracker shows how the matches array fills up with each found match. Key moments clarify why preg_match_all finds multiple matches, what is stored, and why we print matches[0]. The quiz tests understanding of match count, storage step, and behavior when no matches exist. This helps beginners see how preg_match_all works step-by-step.

Practice

(1/5)
1. What does the PHP function preg_match_all do?
easy
A. Splits a string into an array using a pattern.
B. Finds only the first match of a pattern in a string.
C. Replaces all matches of a pattern in a string with another string.
D. Finds all matches of a pattern in a string and stores them in an array.

Solution

  1. Step 1: Understand the function purpose

    preg_match_all is designed to find every occurrence of a pattern in a string, not just the first one.
  2. Step 2: Compare with other functions

    preg_match finds only the first match, preg_replace replaces matches, and preg_split splits strings. So only preg_match_all finds all matches and stores them.
  3. Final Answer:

    Finds all matches of a pattern in a string and stores them in an array. -> Option D
  4. Quick Check:

    preg_match_all = all matches found [OK]
Hint: preg_match_all finds every match, not just one [OK]
Common Mistakes:
  • Confusing preg_match_all with preg_match
  • Thinking it replaces matches
  • Assuming it splits strings
2. Which of the following is the correct syntax to use preg_match_all in PHP?
easy
A. preg_match_all($subject, $pattern, $matches);
B. preg_match_all($pattern, $subject, $matches);
C. preg_match_all($pattern, $matches, $subject);
D. preg_match_all($matches, $pattern, $subject);

Solution

  1. Step 1: Recall function parameter order

    The correct order is pattern first, then the string to search (subject), then the array to store matches.
  2. Step 2: Verify options

    Only preg_match_all($pattern, $subject, $matches); follows this order: preg_match_all($pattern, $subject, $matches);
  3. Final Answer:

    preg_match_all($pattern, $subject, $matches); -> Option B
  4. Quick Check:

    Pattern, subject, matches array order [OK]
Hint: Pattern comes first, then string, then matches array [OK]
Common Mistakes:
  • Swapping pattern and subject parameters
  • Placing matches array before subject
  • Using wrong parameter order
3. What will be the output of the following PHP code?
$text = "apple, banana, cherry";
preg_match_all('/\b\w{6}\b/', $text, $matches);
print_r($matches[0]);
medium
A. ["apple"]
B. ["apple", "banana", "cherry"]
C. ["banana", "cherry"]
D. []

Solution

  1. Step 1: Understand the regex pattern

    The pattern /\b\w{6}\b/ matches words with exactly 6 letters.
  2. Step 2: Check the words in the string

    "apple" has 5 letters, "banana" has 6, "cherry" has 6. So only "banana" and "cherry" match.
  3. Final Answer:

    ["banana", "cherry"] -> Option C
  4. Quick Check:

    Words with 6 letters = banana, cherry [OK]
Hint: Count letters to match \w{6} exactly [OK]
Common Mistakes:
  • Including words with length not equal to 6
  • Misunderstanding \b word boundaries
  • Confusing \w with any character
4. Identify the error in this PHP code snippet using preg_match_all:
$text = "one two three";
preg_match_all('/\w+/', $matches, $text);
print_r($matches);
medium
A. The order of parameters is incorrect.
B. The regex pattern is invalid.
C. The variable $matches is not initialized.
D. The print_r function cannot print arrays.

Solution

  1. Step 1: Check parameter order in preg_match_all

    The correct order is pattern, subject string, then matches array. Here, $matches and $text are swapped.
  2. Step 2: Identify the impact

    Passing $matches as the subject and $text as matches causes wrong behavior and no matches found.
  3. Final Answer:

    The order of parameters is incorrect. -> Option A
  4. Quick Check:

    Parameter order matters in preg_match_all [OK]
Hint: Remember: pattern, subject, matches array order [OK]
Common Mistakes:
  • Swapping subject and matches parameters
  • Assuming regex pattern is wrong
  • Thinking print_r can't print arrays
5. You want to extract all email addresses from a text using preg_match_all. Which pattern correctly matches a simple email format (letters, digits, dots, underscores before @, then domain)?
hard
A. '/[\w\.]+@[\w\.]+\.[a-z]{2,}/i'
B. '/\d+@[a-z]+\.[a-z]{2,}/'
C. '/[a-z]+@[a-z]+\.[a-z]{3}/'
D. '/\w+\s+@\s+\w+\.com/'

Solution

  1. Step 1: Analyze the email pattern requirements

    Emails have letters, digits, dots, underscores before @, then domain with dot and extension.
  2. Step 2: Check each pattern

    '/[\w\.]+@[\w\.]+\.[a-z]{2,}/i' matches word characters and dots before @, then domain and extension with at least 2 letters, case insensitive. Others are too restrictive or incorrect.
  3. Final Answer:

    '/[\w\.]+@[\w\.]+\.[a-z]{2,}/i' -> Option A
  4. Quick Check:

    Pattern includes letters, digits, dots, underscores [OK]
Hint: Use \w and dot before @, domain with dot and 2+ letters [OK]
Common Mistakes:
  • Using \d+ only before @ (digits only)
  • Forcing exact 3-letter domain extensions
  • Adding spaces inside email pattern
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard