Chapter 7: Backreferences, Subroutines & Recursion
Goal: Match repeated text and handle simple nested structures.
1) Backreferences
A backreference lets you match exactly the same text that was captured by a previous group.
Numbered backreferences \1, \2, …
// Match repeated words like "hello hello"
preg_match('/\b(\w+)\s+\1\b/', 'hello hello world', $matches);
echo $matches[0]; // "hello hello"
Group 1 captured hello, \1 requires the same string again.
Named backreferences \k<name>
Easier to read when you have multiple groups:
preg_match('/\b(?<word>\w+)\s+\k<word>\b/', 'test test', $matches);
echo $matches[0]; // "test test"
Matching quotes
preg_match('/(["\'])(.*?)\1/', '"hello"', $matches);
echo $matches[0]; // '"hello"'
Group 1 captures either " or ', \1 forces the same one at the end. Note we use (.*?) (lazy) to avoid consuming too much.
2) Subroutines (?1), (?&name)
A subroutine reuses the pattern of another group: it runs that group’s regex again at the current position. Captures made during the call last only until it returns: afterwards, the group holds what it held before. The difference from a backreference is what gets repeated: \1 repeats captured text, (?1) repeats a pattern. Think of it as “insert this group’s recipe here”.
Numbered subroutine
// Reuse group 1's pattern
preg_match('/(a)(?1)/', 'aa', $matches);
echo $matches[0]; // "aa"
Group 1 matches a, (?1) runs the same pattern again (a).
Named subroutine
preg_match('/(?<char>a)(?&char)/', 'aa', $matches);
echo $matches[0]; // "aa"
3) Recursion (?R)
(?R) calls the entire pattern again from the start. This is useful for matching balanced structures like parentheses or brackets.
// Match balanced parentheses (one level or nested)
$pattern = '/\((?:[^()]|(?R))*\)/';
preg_match($pattern, '(hello)', $matches);
echo $matches[0]; // "(hello)"
preg_match($pattern, '(a(b)c)', $matches);
echo $matches[0]; // "(a(b)c)"
How it works
\(matches opening paren(?:[^()]|(?R))*matches either non-paren characters, or a nested balanced pair via(?R)\)matches closing paren[^()]consumes ordinary characters, and the*allows zero repetitions. That*is the base case, the part that lets an inner call finish without recursing again:()matches with nothing between the parentheses. (A base case, as in any recursion, is what lets the pattern eventually match instead of calling itself forever.)
Important: A recursive pattern must have some way to match without recursing. If every alternative recurses, it won’t work.
A worked trace on "(a(b)c)"
\(consumes the opening(.- The repeated alternation starts:
ais not a paren, so the[^()]branch matches it. - The next character is
(.[^()]cannot match it, so the(?R)branch runs the whole pattern again, starting at that(. The inner run consumes(, matchesbvia[^()], and consumes)— it has matched(b)without recursing again, so it can return. - Back in the outer run, the alternation continues:
cmatches via[^()], then\)consumes the final). - The outer run has matched
(a(b)c)— the whole subject.
4) Conditionals (?(...)yes|no)
Conditionals let you do “if this group matched, do X, else do Y”.
Based on a numbered group
Read (?(1)b|c) as: if group 1 took part in the match, match b here, otherwise match c. “Took part” means the group was used on this attempt: an optional group that was skipped, like (a)? on "c", did not take part, but a group that matched the empty string, like (a*), did, so /^(a*)(?(1)b|c)/ still requires b.
// (?(1)b|c): group 1 took part -> require 'b'; otherwise -> require 'c'
$pattern = '/^(a)?(?(1)b|c)/';
preg_match($pattern, 'ab', $matches); // matches: (a) captured 'a', so 'b' is required
echo $matches[0], PHP_EOL;
preg_match($pattern, 'c', $matches); // matches: (a) matched nothing, so 'c' runs
echo $matches[0], PHP_EOL;
preg_match($pattern, 'ac'); // no match: group 1 took part, so 'b' is required
echo preg_match($pattern, 'ac'), PHP_EOL; // 0
Based on a named group
$pattern = '/^(?<has>a)?(?(has)b|c)/';
preg_match($pattern, 'ab', $matches); // matches
echo $matches[0], PHP_EOL;
preg_match($pattern, 'c', $matches); // matches
echo $matches[0], PHP_EOL;
5) Practical Tips
- Backreferences = “match the same text again”
- Subroutines = “run this group’s pattern again”
- Recursion = “run the whole pattern again”
- For most real tasks, you’ll use backreferences far more than recursion
- Matching arbitrary nested HTML with regex is tricky — a proper parser is usually the better choice
6) Exercises
Exercise 1: Repeated word
Write a pattern to match doubled words like the the using a named group and \k<name>.
Solution
'/\b(?<word>\w+)\s+\k<word>\b/'
Exercise 2: Matching quotes
Write a pattern that matches text inside matching single or double quotes.
Solution
'/(["\'])(.*?)\1/'
Exercise 3: Balanced parentheses
Write a pattern that matches (hello) and (a(b)c) using (?R).
Solution
'/\((?:[^()]|(?R))*\)/'
Exercise 4: Balanced square brackets
Adapt the pattern from the previous exercise so it matches balanced square brackets: it should match [a[b]c] but not [a[b.
Solution
'/\[(?:[^\[\]]|(?R))*\]/'
The shape is identical — escape both brackets, and put neither bracket inside the character class.
Exercise 5: Conditional
Write a pattern that matches ab if a is present, else matches c. Use a named group.
Solution
'/(?<a>a)?(?(a)b|c)/'
Key Takeaways
- Backreferences
\1,\k<name>repeat captured text - Subroutines
(?1),(?&name)repeat a group’s pattern - Recursion
(?R)repeats the whole pattern (great for balanced pairs) - Conditionals
(?(group)yes|no)add simple logic - Always include a base case when using recursion
Common Pitfalls
- Confusing backreference and subroutine —
\1= same text,(?1)= same pattern - Recursion without base case — will fail or behave badly
- Trying to fully parse HTML/XML — regex can do small balanced bits, but parsers are safer
- Backreference to non-existent group — will cause errors
Optional: Tools to Inspect Patterns
vendor/bin/regex explain '/\b(\w+)\s+\1\b/'
vendor/bin/regex diagram '/(["\'])(.*?)\1/'
use PHPRegex\Toolkit\Regex;
$regex = Regex::create();
echo $regex->explain('/(?<word>\w+)\s+\k<word>\b/');