SyntaxStudy
Sign Up
PHP Named Capture Groups in PHP
PHP Intermediate 5 min read

Named Capture Groups in PHP

Named Capture Groups

Use (?P<name>...) in PHP PCRE to name capture groups. Access them via $matches["name"].

Example
<?php
$log = "2024-06-15 10:30:00 [ERROR] Connection refused";

$pattern = "/(?P<date>\d{4}-\d{2}-\d{2}) (?P<time>\d{2}:\d{2}:\d{2}) \[(?P<level>\w+)\] (?P<message>.+)/";

if (preg_match($pattern, $log, $matches)) {
    echo $matches["date"];    // "2024-06-15"
    echo $matches["level"];   // "ERROR"
    echo $matches["message"]; // "Connection refused"
}

// Named groups in preg_replace
$result = preg_replace(
    "/(?P<year>\d{4})-(?P<month>\d{2})-(?P<day>\d{2})/",
    "${day}/${month}/${year}",
    "2024-06-15"
);
// "15/06/2024"
Pro Tip

Named groups self-document patterns — ${year} is clearer than $1 when patterns have many capture groups.