Named Capture Groups
Use (?P<name>...) in PHP PCRE to name capture groups. Access them via $matches["name"].
Use (?P<name>...) in PHP PCRE to name capture groups. Access them via $matches["name"].
<?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"
Named groups self-document patterns — ${year} is clearer than $1 when patterns have many capture groups.