0
0
PHPprogramming~20 mins

Capturing groups and backreferences in PHP - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Regex Backreference Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
What is the output of this PHP code using capturing groups?
Consider the following PHP code that uses a regular expression with capturing groups. What will it output?
PHP
<?php
$subject = "apple banana apple";
$pattern = '/(apple) (banana) \1/';
if (preg_match($pattern, $subject, $matches)) {
    echo $matches[0];
} else {
    echo "No match";
}
?>
Aapple banana apple
Bapple banana banana
CNo match
Dbanana apple banana
Attempts:
2 left
💡 Hint
Remember that \1 refers to the first captured group in the pattern.
Predict Output
intermediate
2:00remaining
What does this PHP code output with nested capturing groups?
Look at this PHP code using nested capturing groups and backreferences. What will it print?
PHP
<?php
$subject = "abcabc";
$pattern = '/(abc)(\1)/';
if (preg_match($pattern, $subject, $matches)) {
    echo count($matches);
} else {
    echo "No match";
}
?>
ANo match
B3
C2
D4
Attempts:
2 left
💡 Hint
Count how many capturing groups are matched and stored in $matches.
🔧 Debug
advanced
2:00remaining
Why does this PHP regex fail to match?
This PHP code tries to match repeated words using backreferences but fails. What is the cause?
PHP
<?php
$subject = "test test";
$pattern = "/(\w+) \1/";
if (preg_match($pattern, $subject)) {
    echo "Matched!";
} else {
    echo "No match";
}
?>
ABackreference \1 is not recognized because it needs double escaping in PHP strings.
BThe pattern misses a quantifier to repeat the word.
CThe subject string has extra spaces causing mismatch.
DThe pattern is correct and will match 'test test'.
Attempts:
2 left
💡 Hint
Check how PHP interprets backslashes inside single-quoted vs double-quoted strings.
📝 Syntax
advanced
2:00remaining
Which option causes a syntax error in PHP regex with capturing groups?
Identify which PHP regex pattern will cause a syntax error when used in preg_match.
A'/(foo|bar)/'
B'/(foo)(bar)/'
C'/(foo)\1/'
D'/(foo(bar)/'
Attempts:
2 left
💡 Hint
Look for unbalanced parentheses in the pattern.
🚀 Application
expert
2:00remaining
How many matches does this PHP code find using backreferences?
This PHP code uses preg_match_all with a pattern that uses backreferences. How many matches will it find?
PHP
<?php
$subject = "cat cat dog dog cat";
$pattern = '/(\w+) \1/';
preg_match_all($pattern, $subject, $matches);
echo count($matches[0]);
?>
A1
B3
C2
D0
Attempts:
2 left
💡 Hint
Look for repeated words separated by a space in the subject string.