0
0
PHPprogramming~10 mins

Capturing groups and backreferences 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 a word using a capturing group.

PHP
<?php
$pattern = '/(\w+)[1]/';
$text = 'Hello';
if (preg_match($pattern, $text, $matches)) {
    echo $matches[1];
}
?>
Drag options to blanks, or click blank then click option'
A+
B*
C?
D{2}
Attempts:
3 left
💡 Hint
Common Mistakes
Using '*' matches zero or more, which might match empty strings.
Using '?' matches zero or one, which might not capture the full word.
2fill in blank
medium

Complete the code to use a backreference to match repeated words.

PHP
<?php
$pattern = '/(\w+)[1]\1/';
$text = 'hello hello';
if (preg_match($pattern, $text)) {
    echo 'Match found';
}
?>
Drag options to blanks, or click blank then click option'
A\d+
B\S+
C\w+
D\s+
Attempts:
3 left
💡 Hint
Common Mistakes
Using \d+ matches digits, not spaces.
Using \w+ matches word characters, which won't match spaces.
3fill in blank
hard

Fix the error in the pattern to correctly match a repeated word using backreference.

PHP
<?php
$pattern = '/(\w+)[1]\1/';
$text = 'test test';
if (preg_match($pattern, $text)) {
    echo 'Repeated word found';
}
?>
Drag options to blanks, or click blank then click option'
A\d+
B\w+
C\s+
D\S+
Attempts:
3 left
💡 Hint
Common Mistakes
Using \w+ or \d+ which do not match spaces.
Not escaping the backslash properly.
4fill in blank
hard

Fill both blanks to create a pattern that matches a word repeated twice with a space between.

PHP
<?php
$pattern = '/([1])[2]\1/';
$text = 'echo echo';
if (preg_match($pattern, $text)) {
    echo 'Match!';
}
?>
Drag options to blanks, or click blank then click option'
A\\w+
B\\d+
C\\s+
D\\S+
Attempts:
3 left
💡 Hint
Common Mistakes
Using \d+ for the word, which matches digits only.
Using \S+ for the space, which matches non-space characters.
5fill in blank
hard

Fill all three blanks to create a pattern that matches a repeated word separated by a comma and space.

PHP
<?php
$pattern = '/([1])[2]\1[3]/';
$text = 'word, word ';
if (preg_match($pattern, $text)) {
    echo 'Pattern matched';
}
?>
Drag options to blanks, or click blank then click option'
A\\w+
B\\s*,\\s*
C\\s+
D,
Attempts:
3 left
💡 Hint
Common Mistakes
Using a literal ', ' for the comma and space, which is less flexible.
Not matching spaces properly around the comma.