Challenge - 5 Problems
Lookahead and Lookbehind Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of positive lookahead regex in PHP
What is the output of this PHP code snippet?
$text = "apple pie and apple tart";
$pattern = '/apple(?= pie)/';
preg_match_all($pattern, $text, $matches);
print_r($matches[0]);
PHP
$text = "apple pie and apple tart"; $pattern = '/apple(?= pie)/'; preg_match_all($pattern, $text, $matches); print_r($matches[0]);
Attempts:
2 left
💡 Hint
Lookahead checks what comes after the word without including it.
✗ Incorrect
The pattern 'apple(?= pie)' matches 'apple' only if it is followed by ' pie'. In the text, only the first 'apple' is followed by ' pie', so only one match is found.
❓ Predict Output
intermediate2:00remaining
Output of negative lookbehind regex in PHP
What will this PHP code output?
$text = "cat bat rat mat";
$pattern = '/(?preg_match_all($pattern, $text, $matches);
print_r($matches[0]);
PHP
$text = "cat bat rat mat"; $pattern = '/(?<!b)at/'; preg_match_all($pattern, $text, $matches); print_r($matches[0]);
Attempts:
2 left
💡 Hint
Negative lookbehind excludes matches preceded by 'b'.
✗ Incorrect
The pattern '(?
🔧 Debug
advanced2:00remaining
Identify the error in this lookbehind regex
This PHP code throws an error. What is the cause?
$pattern = '/(?<=\d+)abc/';
$text = '12abc';
preg_match($pattern, $text, $matches);
PHP
$pattern = '/(?<=\d+)abc/'; $text = '12abc'; preg_match($pattern, $text, $matches);
Attempts:
2 left
💡 Hint
Lookbehind in PHP requires fixed length patterns.
✗ Incorrect
PHP's PCRE engine requires lookbehind patterns to be of fixed length. '(?<=\d+)' is variable length (\d+ can match 1+ digits), which is not supported.
📝 Syntax
advanced2:00remaining
Which regex pattern uses both lookahead and lookbehind correctly?
Which of the following PHP regex patterns correctly matches 'foo' only if it is preceded by 'bar' and followed by 'baz'?
Attempts:
2 left
💡 Hint
Lookbehind checks before, lookahead checks after the match.
✗ Incorrect
Option D uses positive lookbehind '(?<=bar)' to check before 'foo' and positive lookahead '(?=baz)' to check after 'foo'. This correctly matches 'foo' only when preceded by 'bar' and followed by 'baz'.
🚀 Application
expert3:00remaining
Count words not starting with a digit using lookahead
You want to count how many words in the string "$text = '1apple apple 2banana banana 3cherry cherry'" do not start with a digit. Which PHP code snippet correctly counts these words using lookahead?
PHP
$text = '1apple apple 2banana banana 3cherry cherry'; // Your code here
Attempts:
2 left
💡 Hint
Use negative lookahead to exclude words starting with digits and word boundaries to match whole words.
✗ Incorrect
Option B uses negative lookahead '(?!\d)' after '\b' to ensure the word does not start with a digit, and '\b\w+\b' to match whole words. This correctly counts 3 such words.