0
0
PHPprogramming~5 mins

Capturing groups and backreferences in PHP

Choose your learning style9 modes available
Introduction

Capturing groups let you save parts of a text that match a pattern. Backreferences let you use those saved parts again in the same pattern.

When you want to find repeated words in a sentence.
When you need to extract parts of a date like day, month, and year.
When you want to check if a string has matching pairs of characters.
When you want to replace repeated patterns with something else.
Syntax
PHP
/(pattern)/

Parentheses () create a capturing group.

Backreferences use \1, \2, etc., to refer to groups by their order.

Examples
This pattern finds two identical words next to each other, like 'hello hello'.
PHP
/(\w+)\s\1/
This pattern captures a date with day, month, and year parts.
PHP
/(\d{2})-(\d{2})-(\d{4})/
This pattern finds a pair of letters followed by the same pair in reverse order, like 'abba'.
PHP
/(\w)(\w)\2\1/
Sample Program

This program looks for two identical words next to each other in the text. It prints the repeated word if found.

PHP
<?php
$pattern = '/(\w+)\s\1/';
$text = "hello hello world";
if (preg_match($pattern, $text, $matches)) {
    echo "Found repeated word: " . $matches[1] . "\n";
} else {
    echo "No repeated words found.\n";
}
?>
OutputSuccess
Important Notes

Counting of groups starts at 1, not 0.

Backslashes must be doubled in PHP strings to be interpreted correctly.

Captured groups are saved in the $matches array after preg_match.

Summary

Use parentheses () to capture parts of a pattern.

Use backreferences like \1 to reuse captured parts in the same pattern.

Captured parts are available in the matches array after matching.