CodeBlanks Logo Icon CodeBlanks

Capture groups

PHP course · Advanced · Lesson 46/92

Learn to create capture groups with parentheses () and use backreferences.

Capture groups: (...)

Wrapping a piece of the pattern in parentheses makes it a capture group. After preg_match, groups are numbered as $matches[1], $matches[2].

For example, the pattern /(\d{2})\.(\d{2})/ on "29.05" gives $matches[1] = "29" and $matches[2] = "05". $matches[0] always holds the full match.

In preg_replace, captured groups are referenced as $1, $2. To swap date parts, preg_replace("/(\d{2})\.(\d{2})/", "$2.$1", "29.05") works.

Named groups: (?P<name>...)

Naming groups instead of using numbers makes code readable. Write (?P<name>\w+); the match is read with $matches['name'].

Example: after preg_match("/(?P<year>\d{4})/", "in 2026", $m), $m['year'] holds "2026". The number still works: $m[1] is the same.

Since PHP 7, (?<name>...) and (?P<name>...) are equivalent. Named groups are preferred for readability.

Exercise Split first and last name

In $line = "Ayşe Demir";, use preg_match with two capture groups to split first and last name. Write the pattern into $pattern as "/(\w+) (\w+)/u"; the u modifier is needed for the Turkish letters. Print $matches[1] and $matches[2] on separate lines.

Show example solution
Set pattern to "/(\w+) (\w+)/u". Call preg_match($pattern, $line, $matches). Print with echo $matches[1] . "\n"; and echo $matches[2] . "\n";
Example solution:
<?php
// Split first and last name with preg_match capture groups

$line = "Ayşe Demir";
// Set the pattern and matches
$pattern = "/(\w+) (\w+)/u";
preg_match($pattern, $line, $matches);

// Print first and last name
echo $matches[1] . "\n";
echo $matches[2] . "\n";

Test yourself

  1. In preg_replace, how do you reference the whole match?

    • $0
    • $1
    • \g
    • group(0)
    Show answer

    $0 — Correct. $0 is the whole match; $1 and onward are the groups.

  2. Group syntaxes

    (\w+)
    Unnamed capture group
    (?P<name>\w+)
    Named capture group
    $1
    Reference to the first group
    (?:\w+)
    Non-capturing group
  3. Swap the groups

    $new = preg_replace("/(\w+) (\w+)/", "$____ $1", "Ali Veli");
    Show answer
    $new = preg_replace("/(\w+) (\w+)/", "$2 $1", "Ali Veli");

All lessons in Advanced