Complete the code to match a word using a capturing group.
<?php $pattern = '/(\w+)[1]/'; $text = 'Hello'; if (preg_match($pattern, $text, $matches)) { echo $matches[1]; } ?>
The + quantifier matches one or more of the preceding token, so (\w)+ captures one or more word characters.
Complete the code to use a backreference to match repeated words.
<?php $pattern = '/(\w+)[1]\1/'; $text = 'hello hello'; if (preg_match($pattern, $text)) { echo 'Match found'; } ?>
\d+ matches digits, not spaces.\w+ matches word characters, which won't match spaces.The backreference \1 matches the same text as the first capturing group. The \s+ matches one or more whitespace characters between the repeated words.
Fix the error in the pattern to correctly match a repeated word using backreference.
<?php $pattern = '/(\w+)[1]\1/'; $text = 'test test'; if (preg_match($pattern, $text)) { echo 'Repeated word found'; } ?>
\w+ or \d+ which do not match spaces.The pattern needs to match whitespace between the repeated words. Using \s+ fixes the error.
Fill both blanks to create a pattern that matches a word repeated twice with a space between.
<?php $pattern = '/([1])[2]\1/'; $text = 'echo echo'; if (preg_match($pattern, $text)) { echo 'Match!'; } ?>
\d+ for the word, which matches digits only.\S+ for the space, which matches non-space characters.The first blank should capture one or more word characters (\w+), and the second blank should match one or more whitespace characters (\s+) between the repeated words.
Fill all three blanks to create a pattern that matches a repeated word separated by a comma and space.
<?php $pattern = '/([1])[2]\1[3]/'; $text = 'word, word '; if (preg_match($pattern, $text)) { echo 'Pattern matched'; } ?>
The first blank captures one or more word characters (\w+). The second blank matches a comma possibly surrounded by spaces (\s*,\s*). The third blank matches one or more spaces (\s+) after the repeated word.