Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete 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'
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/".
✗ Incorrect
The pattern must be enclosed in delimiters like slashes (/). So, "/cat/" is the correct pattern to find 'cat'.
2fill in blank
mediumComplete 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'
Attempts:
3 left
💡 Hint
Common Mistakes
Using $ which matches the end of the string instead of ^.
Using a pattern that does not include delimiters.
✗ Incorrect
The caret (^) means the start of the string. So, "/^Hello/" checks if the string starts with 'Hello'.
3fill in blank
hardFix 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'
Attempts:
3 left
💡 Hint
Common Mistakes
Using * which allows empty strings.
Not anchoring the pattern with ^ and $.
✗ Incorrect
The pattern "/^[0-9]+$/" matches strings that contain only digits from start to end, with at least one digit.
4fill in blank
hardFill 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'
Attempts:
3 left
💡 Hint
Common Mistakes
Forgetting to escape the dot.
Using wrong domain endings like .net or .edu.
✗ Incorrect
The patterns "/\.com$/" and "/\.org$/" check if the string ends with '.com' or '.org' respectively.
5fill in blank
hardFill 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'
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.
✗ Incorrect
The pattern uses a character class [a-zA-Z0-9._], then * to allow zero or more characters, then the same character class again to match the email username part.