0
0
PHPprogramming~10 mins

Why regex is needed in PHP - Test Your Understanding

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

Complete the code to check if the string contains the word 'apple'.

PHP
<?php
$string = "I like apples.";
if (preg_match([1], $string)) {
    echo "Found apple!";
}
?>
Drag options to blanks, or click blank then click option'
A"^apple$"
B"apple"
C"/apple/i"
D"/apple/"
Attempts:
3 left
💡 Hint
Common Mistakes
Using the word without slashes as pattern causes errors.
Forgetting to use regex delimiters.
2fill in blank
medium

Complete the code to replace all digits in the string with '#'.

PHP
<?php
$text = "My phone is 123-456-7890.";
$result = preg_replace([1], '#', $text);
echo $result;
?>
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 matches letters and digits, not just digits.
Using \s matches spaces, not digits.
3fill in blank
hard

Fix the error in the regex pattern to match an email address.

PHP
<?php
$email = "user@example.com";
if (preg_match([1], $email)) {
    echo "Valid email.";
} else {
    echo "Invalid email.";
}
?>
Drag options to blanks, or click blank then click option'
A"^[\w.-]+@[\w.-]+\.[a-zA-Z]{2,6}$"
B"/^[\w.-]+@[\w.-]+\.[a-zA-Z]{2,6}$/"
C"/^[\w.-]+@[\w.-]+\.[a-zA-Z]{2,6}$/i"
D"/^[\w.-]+@[\w.-]+\.[a-zA-Z]{2,6}/"
Attempts:
3 left
💡 Hint
Common Mistakes
Omitting delimiters causes syntax errors.
Leaving out anchors may cause partial matches.
4fill in blank
hard

Fill both blanks to create a dictionary of words and their lengths for words longer than 3 characters.

PHP
<?php
$words = ['cat', 'elephant', 'dog', 'horse'];
$lengths = array_filter(array_map(function($word) {
    return strlen($word);
}, $words), function($word) {
    return $word [1] 3;
});
print_r($lengths);
?>
Drag options to blanks, or click blank then click option'
A==
B<
C>
D!=
Attempts:
3 left
💡 Hint
Common Mistakes
Using < or == will not filter correctly.
Using != will include unwanted words.
5fill in blank
hard

Fill all three blanks to create an associative array of uppercase words and their lengths for words longer than 4 characters.

PHP
<?php
$words = ['apple', 'bat', 'carrot', 'dog'];
$result = array_filter(array_combine(array_map(function($word) {
    return [1];
}, $words), array_map(function($word) {
    return [2];
}, $words)), function($length) {
    return $length [3] 4;
});
print_r($result);
?>
Drag options to blanks, or click blank then click option'
Astrtoupper($word)
Bstrlen($word)
C>
Dstrtolower($word)
Attempts:
3 left
💡 Hint
Common Mistakes
Using strtolower instead of strtoupper.
Using wrong comparison operators like < or ==.