0
0
PHPprogramming~5 mins

Capturing groups and backreferences in PHP - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is a capturing group in a regular expression?
A capturing group is a part of a regular expression enclosed in parentheses (). It saves the matched text so you can use it later in your code or in the same pattern.
Click to reveal answer
beginner
How do you refer to a captured group inside the same regular expression?
You use a backreference, which is written as \1, \2, etc., where the number matches the order of the capturing group.
Click to reveal answer
intermediate
Example: What does the pattern '/(\w+) \1/' match?
It matches two identical words next to each other, like 'hello hello'. The first (\w+) captures a word, and \1 checks if the next word is the same.
Click to reveal answer
intermediate
In PHP, how do you access the text matched by capturing groups after using preg_match?
The matched groups are stored in an array passed by reference to preg_match. The full match is at index 0, and captured groups start from index 1.
Click to reveal answer
beginner
Why are capturing groups useful in programming?
They let you extract parts of a string easily, reuse matched text, and perform complex text manipulations like swapping words or validating repeated patterns.
Click to reveal answer
What symbol is used to create a capturing group in a regular expression?
A()
B[]
C{}
D<>
In PHP regex, what does \2 refer to?
AThe second word in the string
BThe second character in the string
CThe second line of input
DThe second capturing group
What will '/(\d+)\1/' match in the string '123123'?
AAny digits
BOnly one digit
CTwo identical sequences of digits in a row
DNo match
After preg_match('/(foo)(bar)/', 'foobar', $matches), what is in $matches[1]?
Anull
Bfoo
Cfoobar
Dbar
Which of these is NOT a use of capturing groups?
AChanging the case of letters automatically
BReusing matched text in the same regex
CExtracting parts of a string
DValidating repeated patterns
Explain what capturing groups and backreferences are and how they work together in regular expressions.
Think about how you can remember and reuse parts of a matched string.
You got /4 concepts.
    Describe how you would use capturing groups and backreferences in PHP to find repeated words in a sentence.
    Focus on matching a word and then the same word again.
    You got /4 concepts.