Bird
Raised Fist0
PHPprogramming~10 mins

Capturing groups and backreferences in PHP - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Capturing groups and backreferences
Start regex
↓
Find ( ) capturing group
↓
Match pattern inside group
↓
Store matched text
↓
Use backreference \1 to match same text again
↓
Full pattern matched?
No→Fail
Yes↓
Return match with captured groups
The regex engine finds text matching the pattern inside parentheses, stores it, then uses \1 to match the same text again.
Execution Sample
PHP
<?php
$pattern = '/(\w+) \1/';
$subject = 'hello hello world';
preg_match($pattern, $subject, $matches);
print_r($matches);
?>
This code finds repeated words like 'hello hello' using a capturing group and backreference.
Execution Table
StepRegex PositionActionMatched TextCaptured Group 1Backreference \1 MatchResult
1StartBegin matching at start of subjectContinue
2(\w+)Match first word charactershellohelloContinue
3 Match space character helloContinue
4\1Match same text as group 1hellohellohelloContinue
5EndPattern fully matchedhello hellohellohelloMatch found
6After matchStop searchinghellohelloExit
💡 Pattern matched 'hello hello' and stopped searching further.
Variable Tracker
VariableStartAfter Step 2After Step 4Final
Captured Group 1hellohellohello
Backreference \1hellohello
Key Moments - 2 Insights
Why does the backreference \1 match the same text as the first group?
Because \1 refers exactly to the text captured by the first parentheses group, as shown in execution_table step 4.
What happens if the backreference \1 does not find the same text?
The pattern fails to match and the regex engine stops, as no full match is found (not shown in this successful trace).
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what text is captured by group 1 at step 2?
Ahello
Bworld
Chello hello
D\1
💡 Hint
Check the 'Captured Group 1' column at step 2 in the execution_table.
At which step does the backreference \1 successfully match the same text?
AStep 2
BStep 4
CStep 5
DStep 6
💡 Hint
Look at the 'Backreference \1 Match' column in the execution_table.
If the subject was 'hello world', what would happen to the match?
AMatch found with 'hello world'
BNo match because backreference \1 fails
CMatch found with 'world world'
DMatch found with 'hello hello'
💡 Hint
Backreference \1 must match the exact text captured by group 1; see key_moments about failure.
Concept Snapshot
Capturing groups use parentheses ( ) to save matched text.
Backreferences like \1 match the exact text from the first group.
Used to find repeated patterns, e.g., repeated words.
If backreference fails, the whole match fails.
Syntax example: /(\w+) \1/ matches repeated words.
Full Transcript
This example shows how PHP regex uses capturing groups and backreferences. The pattern /(\w+) \1/ looks for a word, then the same word again separated by space. Step by step, the regex matches 'hello' as group 1, then matches a space, then uses \1 to match the same 'hello' again. The match succeeds with 'hello hello'. Variables track the captured group and backreference text. If the backreference does not match, the pattern fails. This helps find repeated text patterns easily.

Practice

(1/5)
1. What does a capturing group in a PHP regular expression do?
easy
A. It ignores the matched text inside parentheses.
B. It repeats the entire pattern multiple times.
C. It saves part of the matched text for later use.
D. It changes the case of matched text.

Solution

  1. Step 1: Understand capturing groups

    Parentheses () in regex save the matched part for reuse.
  2. Step 2: Purpose of capturing groups

    This saved part can be accessed later in the code or reused in the pattern.
  3. Final Answer:

    It saves part of the matched text for later use. -> Option C
  4. Quick Check:

    Capturing group = save matched text [OK]
Hint: Parentheses capture text to reuse later in regex or code [OK]
Common Mistakes:
  • Thinking capturing groups repeat patterns
  • Believing they ignore matched text
  • Assuming they change text case
2. Which of the following is the correct syntax for a backreference to the first capturing group in a PHP regex pattern?
easy
A. \(1\)
B. \\1
C. \$1
D. \1

Solution

  1. Step 1: Identify backreference syntax in PHP regex

    Backreferences use a single backslash followed by group number, like \1 in regex patterns.
  2. Step 2: Differentiate from string escaping

    In PHP strings, to represent \1 you write "\\1" but the regex pattern itself uses \1.
  3. Final Answer:

    \1 -> Option D
  4. Quick Check:

    Backreference first group = \1 [OK]
Hint: Use single backslash before group number for backreference in regex [OK]
Common Mistakes:
  • Using double backslash instead of single
  • Confusing backreference with variable syntax
  • Adding parentheses around the number
3. What will be the output of the following PHP code?
$pattern = '/(\w+)\s\1/';
$subject = 'hello hello world';
if (preg_match($pattern, $subject, $matches)) {
    echo $matches[0];
} else {
    echo 'No match';
}
medium
A. hello world
B. hello hello
C. No match
D. hello

Solution

  1. Step 1: Understand the regex pattern

    The pattern /(\w+)\s\1/ matches a word, a space, then the same word again (backreference \1).
  2. Step 2: Apply pattern to the subject string

    The string 'hello hello world' contains 'hello hello' which matches the pattern.
  3. Final Answer:

    hello hello -> Option B
  4. Quick Check:

    Backreference matches repeated word = hello hello [OK]
Hint: Backreference \1 matches exact previous captured word [OK]
Common Mistakes:
  • Ignoring backreference meaning
  • Matching different words instead of repeated
  • Expecting full string match
4. Identify the error in this PHP regex pattern: preg_match('/(\d+)\s\2/', '123 123', $matches);
medium
A. Backreference \2 is invalid because only one group is captured.
B. The pattern should use \1 instead of \2 for backreference.
C. The pattern is missing delimiters.
D. The pattern should not use capturing groups.

Solution

  1. Step 1: Count capturing groups in the pattern

    There is only one capturing group: (\d+), so only \1 is valid.
  2. Step 2: Check backreference usage

    Using \2 refers to a second group which does not exist, causing an error.
  3. Final Answer:

    Backreference \2 is invalid because only one group is captured. -> Option A
  4. Quick Check:

    Backreference number must match captured groups [OK]
Hint: Backreference number must not exceed captured groups count [OK]
Common Mistakes:
  • Using backreference number higher than groups
  • Ignoring missing groups
  • Confusing delimiters with backreferences
5. Given the string 'abc123abc456', which regex pattern using capturing groups and backreferences will match the repeated substring 'abc' only if it appears twice separated by digits?
hard
A. /(abc)\d+\1/
B. /(abc)\1\d+/
C. /abc(\d+)abc/
D. /(abc)+\d+/

Solution

  1. Step 1: Understand the requirement

    We want to match 'abc' repeated twice with digits in between.
  2. Step 2: Analyze each pattern

    /(abc)\d+\1/: /(abc)\d+\1/ matches 'abc', digits, then same 'abc' again. This fits the requirement.
    /(abc)\1\d+/: /(abc)\1\d+/ expects 'abcabc' then digits, which is incorrect.
    /abc(\d+)abc/: /abc(\d+)abc/ matches 'abc', digits, 'abc' but digits are captured, not 'abc'.
    /(abc)+\d+/: /(abc)+\d+/ matches one or more 'abc' then digits, but no backreference to ensure repetition.
  3. Final Answer:

    /(abc)\d+\1/ -> Option A
  4. Quick Check:

    Backreference \1 repeats captured 'abc' after digits [OK]
Hint: Backreference \1 repeats first group exactly where needed [OK]
Common Mistakes:
  • Placing backreference before digits
  • Not using backreference to repeat 'abc'
  • Capturing digits instead of 'abc'
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard