Challenge - 5 Problems
Preg_match_all Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
What is the output of preg_match_all with a simple pattern?
Consider the following PHP code snippet using
preg_match_all. What will be the output?PHP
<?php $subject = 'apple banana apple cherry'; $pattern = '/apple/'; preg_match_all($pattern, $subject, $matches); print_r($matches[0]); ?>
Attempts:
2 left
💡 Hint
preg_match_all finds all matches, not just the first one.
✗ Incorrect
The pattern '/apple/' matches the word 'apple' twice in the string. preg_match_all collects all matches in $matches[0].
❓ Predict Output
intermediate2:00remaining
How many matches does preg_match_all find?
Given this PHP code, how many matches will
preg_match_all find?PHP
<?php $subject = 'cat bat rat mat'; $pattern = '/.at/'; $count = preg_match_all($pattern, $subject, $matches); echo $count; ?>
Attempts:
2 left
💡 Hint
The pattern matches any character followed by 'at'.
✗ Incorrect
The pattern '/.at/' matches 'cat', 'bat', 'rat', and 'mat' — four matches total.
🔧 Debug
advanced2:00remaining
Why does this preg_match_all code produce an empty array?
Look at this PHP code. Why does
preg_match_all return no matches?PHP
<?php $subject = '123-456-7890'; $pattern = '/\d{3}-\d{3}-\d{4}/'; preg_match_all($pattern, $subject, $matches); print_r($matches[0]); ?>
Attempts:
2 left
💡 Hint
Check how backslashes are used inside PHP strings for regex.
✗ Incorrect
In PHP, backslashes must be escaped in double-quoted strings. The pattern should be '/\\d{3}-\\d{3}-\\d{4}/' or use single quotes to avoid double escaping.
📝 Syntax
advanced2:00remaining
Which option causes a syntax error in preg_match_all usage?
Identify which PHP code snippet will cause a syntax error when using
preg_match_all.Attempts:
2 left
💡 Hint
Check the type of the fourth argument in preg_match_all.
✗ Incorrect
The fourth argument must be an integer flag, not a string. Using 'PREG_OFFSET_CAPTURE' as a string causes a syntax error.
🚀 Application
expert3:00remaining
Extract all email addresses from a text using preg_match_all
You want to extract all email addresses from a string using
preg_match_all. Which code snippet correctly captures all emails?Attempts:
2 left
💡 Hint
Remember PHP regex does not use 'g' flag and preg_match_all finds all matches.
✗ Incorrect
Option B uses the correct pattern and preg_match_all to find all emails. Option B uses 'g' which is invalid in PHP. Option B adds 'i' for case-insensitive but is optional. Option B uses preg_match which finds only the first match.