0
0
PHPprogramming~10 mins

Character classes and quantifiers in PHP - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to match any digit character using a regular expression.

PHP
<?php
$pattern = '/[1]/';
$string = 'My number is 1234';
if (preg_match($pattern, $string)) {
    echo 'Digit found';
} else {
    echo 'No digit found';
}
?>
Drag options to blanks, or click blank then click option'
A\d
B\w
C\s
D\D
Attempts:
3 left
💡 Hint
Common Mistakes
Using \w which matches letters and digits, not only digits.
Using \s which matches whitespace characters.
2fill in blank
medium

Complete the code to match exactly three lowercase letters in a row.

PHP
<?php
$pattern = '/[a-z][1]/';
$string = 'abc def';
if (preg_match($pattern, $string)) {
    echo 'Match found';
} else {
    echo 'No match';
}
?>
Drag options to blanks, or click blank then click option'
A{3}
B{2,4}
C*
D+
Attempts:
3 left
💡 Hint
Common Mistakes
Using + which matches one or more, not exactly three.
Using * which matches zero or more.
3fill in blank
hard

Fix the error in the pattern to match one or more whitespace characters.

PHP
<?php
$pattern = '/\s[1]/';
$string = "Hello   World";
if (preg_match($pattern, $string)) {
    echo 'Whitespace found';
} else {
    echo 'No whitespace';
}
?>
Drag options to blanks, or click blank then click option'
A*
B+
C?
D{1,}
Attempts:
3 left
💡 Hint
Common Mistakes
Using ? which means zero or one occurrence.
Using * which means zero or more, but the question asks for one or more.
4fill in blank
hard

Fill both blanks to create a pattern that matches a string starting with one or more digits followed by exactly two letters.

PHP
<?php
$pattern = '/^[1][a-z][2]$/';
$string = '123ab';
if (preg_match($pattern, $string)) {
    echo 'Pattern matches';
} else {
    echo 'No match';
}
?>
Drag options to blanks, or click blank then click option'
A\d+
B[a-z]
C{2}
D[0-9]
Attempts:
3 left
💡 Hint
Common Mistakes
Using [0-9] without quantifier for digits.
Not specifying exact two letters with {2}.
5fill in blank
hard

Fill all three blanks to create a pattern that matches a string with exactly three uppercase letters, followed by one or more digits, and ending with zero or more whitespace characters.

PHP
<?php
$pattern = '/^[1][2][3]$/';
$string = 'ABC123   ';
if (preg_match($pattern, $string)) {
    echo 'Full match';
} else {
    echo 'No full match';
}
?>
Drag options to blanks, or click blank then click option'
A[A-Z]{3}
B\d+
C\s*
D[a-z]{3}
Attempts:
3 left
💡 Hint
Common Mistakes
Using lowercase letters instead of uppercase.
Using wrong quantifiers for digits or whitespace.