Back to results for “Match”
PHP › Regular Expressions in PHP

What are named capture groups in a regular expression, and how do they improve the readability of extracted match data compared to using only numbered groups?

Intermediate

Answer

A named capture group lets you assign a descriptive name to a specific part of your pattern using a special syntax, and when a match is found, you can access that specific captured portion using its assigned name rather than needing to remember and count numbered positions, which significantly improves the readability and maintainability of code that extracts and uses several different pieces of matched data from a single pattern.
preg_match('/(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/', '2026-09-07', $matches);
echo $matches['year'];
Real-world example A date parsing function uses named capture groups for year, month, and day, making the code that later accesses each specific piece of the parsed date immediately clear and self documenting, compared to remembering that group three specifically represents the day.

Common follow-ups: Can you mix named and numbered capture groups within the same pattern?;How does using named groups affect the overall performance of the regular expression?