0
0
PHPprogramming~10 mins

Preg_match for pattern matching 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 check if the string contains the word 'cat'.

PHP
<?php
$string = "The cat is sleeping.";
if (preg_match([1], $string)) {
    echo "Found a cat!";
} else {
    echo "No cat found.";
}
?>
Drag options to blanks, or click blank then click option'
A"cat"
B"/dog/"
C"/cat/"
D"/Cat/"
Attempts:
3 left
💡 Hint
Common Mistakes
Using the pattern without slashes, like "cat" instead of "/cat/".
Using the wrong word in the pattern, like "/dog/".
2fill in blank
medium

Complete the code to check if the string starts with 'Hello'.

PHP
<?php
$string = "Hello world!";
if (preg_match([1], $string)) {
    echo "Starts with Hello.";
} else {
    echo "Does not start with Hello.";
}
?>
Drag options to blanks, or click blank then click option'
A"/world/"
B"/^Hello/"
C"/^world/"
D"/Hello$/"
Attempts:
3 left
💡 Hint
Common Mistakes
Using $ which matches the end of the string instead of ^.
Using a pattern that does not include delimiters.
3fill in blank
hard

Fix the error in the pattern to check if the string contains only digits.

PHP
<?php
$string = "12345";
if (preg_match([1], $string)) {
    echo "Only digits.";
} else {
    echo "Contains other characters.";
}
?>
Drag options to blanks, or click blank then click option'
A"/\d*$/"
B"/^[0-9]*$/"
C"/\d+/"
D"/^[0-9]+$/"
Attempts:
3 left
💡 Hint
Common Mistakes
Using * which allows empty strings.
Not anchoring the pattern with ^ and $.
4fill in blank
hard

Fill both blanks to create a pattern that matches strings ending with '.com' or '.org'.

PHP
<?php
$string = "example.com";
if (preg_match([1], $string) || preg_match([2], $string)) {
    echo "Valid domain.";
} else {
    echo "Invalid domain.";
}
?>
Drag options to blanks, or click blank then click option'
A"/\.com$/"
B"/\.net$/"
C"/\.org$/"
D"/\.edu$/"
Attempts:
3 left
💡 Hint
Common Mistakes
Forgetting to escape the dot.
Using wrong domain endings like .net or .edu.
5fill in blank
hard

Fill all three blanks to create a pattern that matches a valid email address with letters, digits, dots, and underscores before '@'.

PHP
<?php
$email = "user.name_123@example.com";
$pattern = "/^[[1]][2][[3]]+@example\.com$/";
if (preg_match($pattern, $email)) {
    echo "Valid email.";
} else {
    echo "Invalid email.";
}
?>
Drag options to blanks, or click blank then click option'
Aa-zA-Z0-9._
B+
C*
D-
Attempts:
3 left
💡 Hint
Common Mistakes
Using + which requires at least one character in the middle part.
Not including all allowed characters in the class.