0
0
PHPprogramming~20 mins

Character classes and quantifiers in PHP - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Regex Mastery in PHP
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2: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]);
?>
AArray ( [0] => abca [1] => bcab )
BArray ( [0] => ab [1] => ca [2] => bc )
CArray ( [0] => a [1] => b [2] => c )
DArray ( [0] => abc [1] => abc [2] => abc )
Attempts:
2 left
💡 Hint
Look at the pattern: it matches 2 to 4 characters from a to c.
Predict Output
intermediate
2: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]);
?>
AArray ( [0] => a1b [1] => 2c3 [2] => d4 )
BArray ( [0] => b2c )
CArray ( [0] => bcd )
DArray ( [0] => abc )
Attempts:
2 left
💡 Hint
The pattern matches 3 characters that are NOT digits.
🔧 Debug
advanced
2: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);
?>
ARuntimeError: preg_match failed due to invalid pattern
BNo error, matches 'abc'
CSyntaxError: Quantifier range is invalid because 3 is greater than 2
DTypeError: preg_match expects string, got array
Attempts:
2 left
💡 Hint
Check the quantifier {3,2} carefully.
📝 Syntax
advanced
2:00remaining
Which regex pattern matches exactly 1 or 2 digits?
Choose the correct regex pattern that matches exactly one or two digits in PHP.
A'/\d{1,2}/'
B'/\d{1,}/'
C'/\d{,2}/'
D'/\d{2,1}/'
Attempts:
2 left
💡 Hint
Quantifiers specify minimum and maximum counts in the form {min,max}.
🚀 Application
expert
3: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?
A
&lt;?php
preg_match_all('/\b[a-zA-Z]{3,5}/', $text, $matches);
echo count($matches[0]);
?&gt;
B
&lt;?php
preg_match_all('/\b[a-z]{3,5}\b/i', $text, $matches);
echo count($matches[0]);
?&gt;
C
&lt;?php
preg_match_all('/\b[a-zA-Z]{3,5}\b/', $text, $matches);
echo count($matches[0]);
?&gt;
D
&lt;?php
preg_match_all('/[a-zA-Z]{3,5}\b/', $text, $matches);
echo count($matches[0]);
?&gt;
Attempts:
2 left
💡 Hint
Use word boundaries and case-insensitive flag to match words correctly.