0
0
PHPprogramming~10 mins

Preg_match_all for global 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 find all matches of 'cat' in the string.

PHP
<?php
$subject = "The cat sat on the cat mat.";
preg_match_all([1], $subject, $matches);
print_r($matches[0]);
?>
Drag options to blanks, or click blank then click option'
A"/cat/i"
B"cat"
C"/cat/"
D"/cat/g"
Attempts:
3 left
💡 Hint
Common Mistakes
Using the pattern without slashes causes an error.
Adding 'g' modifier is invalid in PHP regex.
2fill in blank
medium

Complete the code to perform a case-insensitive global match for 'dog'.

PHP
<?php
$subject = "Dog dog DOG doG";
preg_match_all([1], $subject, $matches);
print_r($matches[0]);
?>
Drag options to blanks, or click blank then click option'
A"/dog/i"
B"/dog/"
C"dog"
D"/dog/g"
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'g' modifier which is invalid in PHP.
Not using slashes around the pattern.
3fill in blank
hard

Fix the error in the code to correctly find all numbers in the string.

PHP
<?php
$subject = "123 abc 456 def 789";
preg_match_all([1], $subject, $matches);
print_r($matches[0]);
?>
Drag options to blanks, or click blank then click option'
A"/\d+/"
B"/d+/"
C"/\d*/"
D"/\D+/"
Attempts:
3 left
💡 Hint
Common Mistakes
Not escaping the backslash causes an error.
Using '\D' matches non-digits, which is wrong.
4fill in blank
hard

Fill both blanks to find all words starting with 'a' or 'A' in the string.

PHP
<?php
$subject = "Apple and apricot are awesome.";
preg_match_all([1], $subject, $matches, [2]);
print_r($matches[0]);
?>
Drag options to blanks, or click blank then click option'
A"/\b[aA]\w*/"
BPREG_OFFSET_CAPTURE
CPREG_PATTERN_ORDER
DPREG_SET_ORDER
Attempts:
3 left
💡 Hint
Common Mistakes
Using PREG_SET_ORDER changes the structure of matches.
Not escaping backslashes in the pattern.
5fill in blank
hard

Fill all three blanks to extract all email addresses from the text.

PHP
<?php
$text = "Contact us at support@example.com or sales@example.org.";
preg_match_all([1], $text, $matches, [2], [3]);
print_r($matches[0]);
?>
Drag options to blanks, or click blank then click option'
A"/[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/"
B0
CPREG_PATTERN_ORDER
DPREG_OFFSET_CAPTURE
Attempts:
3 left
💡 Hint
Common Mistakes
Using wrong offset or flags changes output structure.
Incorrect regex pattern misses valid emails.