Challenge - 5 Problems
Regex Mastery in PHP
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of regex match with character classes
What will be the output of this PHP code snippet?
PHP
<?php $pattern = '/[a-c]{2,4}/'; $subject = 'abcabcabc'; preg_match_all($pattern, $subject, $matches); print_r($matches[0]); ?>
Attempts:
2 left
💡 Hint
Look at the pattern: it matches 2 to 4 characters from a to c.
✗ Incorrect
The pattern '/[a-c]{2,4}/' matches sequences of 2 to 4 characters where each character is a, b, or c. In 'abcabcabc', the greedy quantifier takes the maximum of 4: 'abca' (positions 0-3), then 'bcab' (4-7).
❓ Predict Output
intermediate2:00remaining
Result of regex with negated character class
What will this PHP code output?
PHP
<?php $pattern = '/[^0-9]{3}/'; $subject = 'abc123d4'; preg_match_all($pattern, $subject, $matches); print_r($matches[0]); ?>
Attempts:
2 left
💡 Hint
The pattern matches 3 characters that are NOT digits.
✗ Incorrect
The pattern '/[^0-9]{3}/' matches exactly 3 consecutive non-digit characters. In 'abc123d4', 'abc' matches but 'd' is only 1 character.
🔧 Debug
advanced2:00remaining
Identify the error in regex quantifier usage
This PHP code throws an error. What is the cause?
PHP
<?php $pattern = '/[a-z]{3,2}/'; $subject = 'abcdef'; preg_match($pattern, $subject, $matches); print_r($matches); ?>
Attempts:
2 left
💡 Hint
Check the quantifier {3,2} carefully.
✗ Incorrect
Quantifiers in regex must have the lower number first. '{3,2}' is invalid because 3 is greater than 2. This causes a regex compilation error.
📝 Syntax
advanced2:00remaining
Which regex pattern matches exactly 1 or 2 digits?
Choose the correct regex pattern that matches exactly one or two digits in PHP.
Attempts:
2 left
💡 Hint
Quantifiers specify minimum and maximum counts in the form {min,max}.
✗ Incorrect
Option A uses '{1,2}' which means match 1 or 2 digits. Option A means 1 or more digits, option A is invalid syntax, and option A has min greater than max which is invalid.
🚀 Application
expert3:00remaining
Count words with 3 to 5 letters using regex
You want to count how many words in a string have between 3 and 5 letters (only letters a-z, case insensitive). Which PHP code snippet correctly does this?
Attempts:
2 left
💡 Hint
Use word boundaries and case-insensitive flag to match words correctly.
✗ Incorrect
Option B uses word boundaries '\b' to ensure whole words, the character class '[a-z]' with 'i' flag for case insensitivity, and quantifier '{3,5}' to match words with 3 to 5 letters. Other options miss case insensitivity or word boundaries on both sides.