← Home ← Codex ← DEBT ← Engine
Browse by Category
+ added · ✎ updated 7d
← Back to glossary

Named Capture Groups

Regex PHP 5.3+ Intermediate
debt(d7/e3/b3/t5)
d7 Detectability Operational debt — how invisible misuse is to your safety net

Closest to 'only careful code review or runtime testing' (d7), since phpstan/phpcs don't flag numbered group usage as a smell — it requires code review to spot brittle $matches[1] index access.

e3 Effort Remediation debt — work required to fix once spotted

Closest to 'simple parameterised fix' (e3), per quick_fix: rename pattern groups to (?P<name>...) and update $matches[N] to $matches['name'] — small refactor within the regex usage site, possibly a few lines per call site.

b3 Burden Structural debt — long-term weight of choosing wrong

Closest to 'localised tax' (b3), since the choice applies per-regex; impact is on the file using that pattern, not the whole codebase, though regex usage is spread across web/cli/queue contexts.

t5 Trap Cognitive debt — how counter-intuitive correct behaviour is

Closest to 'notable trap' (t5), per misconception: developers underestimate that numbered indices silently shift when groups are added/reordered — a documented gotcha that bites once experienced.

About DEBT scoring →

Also Known As

named capture (?P<n>) PCRE named group

TL;DR

(?P<n>pattern) in PHP/PCRE for self-documenting regex — accessing matches by name instead of positional index.

Explanation

Named capture groups in PHP/PCRE: (?P<n>pattern) or (?<n>pattern). Access via $matches['name'] instead of $matches[1]. Benefits: self-documenting patterns, index-independent (reordering groups does not break code), easier to maintain. Backreferences: (?P=name) in pattern, ${name} in preg_replace replacement strings.

Common Misconception

✗ Numbered groups are just as readable as named groups — $matches[3] is opaque; $matches['year'] is self-documenting. With more than 2-3 groups, names are essential for maintainability.

Why It Matters

A date regex with numeric groups breaks silently if group order changes — named groups ensure $matches['year'] always refers to the year regardless of pattern changes.

Common Mistakes

  • Numbered groups when there are more than 3
  • Not using ${name} in preg_replace replacement strings
  • Naming groups in alternations where only one branch matches — others return empty string
  • Group names with invalid characters — must match [A-Za-z_][A-Za-z0-9_]*

Code Examples

✗ Vulnerable
// Numbered groups — fragile:
preg_match('/(\d{4})-(\d{2})-(\d{2})/', '2026-03-16', $m);
$year  = $m[1]; // Breaks if pattern is reordered
$month = $m[2];
$day   = $m[3];
✓ Fixed
// Named groups — readable and stable:
preg_match('/(?P<year>\d{4})-(?P<month>\d{2})-(?P<day>\d{2})/', '2026-03-16', $m);
$year  = $m['year'];  // Self-documenting
$month = $m['month'];
$day   = $m['day'];

// Named backreference:
preg_match('/<(?P<tag>\w+)>[^<]*<\/(?P=tag)>/', '<b>bold</b>', $m);
// (?P=tag) ensures opening and closing tag are the same

Tags


Added 16 Mar 2026
Edited 5 Apr 2026
Views 225
Rate this term
No ratings yet
🤖 AI Guestbook educational data only
| |
Last 30 days
0 pings F 1 ping S 0 pings S 0 pings M 1 ping T 0 pings W 0 pings T 0 pings F 0 pings S 0 pings S 0 pings M 1 ping T 2 pings W 0 pings T 1 ping F 0 pings S 0 pings S 1 ping M 0 pings T 1 ping W 0 pings T 0 pings F 0 pings S 0 pings S 4 pings M 0 pings T 0 pings W 0 pings T 0 pings F 0 pings S
No pings yet today
No pings yesterday
PetalBot 20 ChatGPT 19 Amazonbot 17 SEMrush 11 Google 10 Ahrefs 10 Bing 9 Scrapy 9 Perplexity 7 Unknown AI 3 Claude 3 Brave Search 3 Twitter/X 2 Applebot 2 DuckDuckGo 2 Meta AI 1 Sogou 1
crawler 125 crawler_json 4
🧱 FUNDAMENTALS — new to this? Start with the ground floor.
Backreference regex A backreference lets a regex match the same text that an earlier group already captured. You write \1 to mean 'whatever group 1 just matched'.

Backreferences turn regex from a static pattern-matcher into something that can enforce 'this must equal that,' which is essential for finding duplicates, matched pairs, and consistent structures in text.

💡 Every \1 needs a matching (group) earlier in the pattern — count your parentheses before you reference them.

Ask Codex about Backreference →
Regex general A regex (regular expression) is a pattern you write to search, match, or replace text. It's like a super-powered find-and-replace that can match flexible patterns instead of exact words.

Regex turns hours of manual text hunting into a single line of code. From form validation to log parsing to data cleanup, pattern matching is everywhere in real-world programming.

💡 When a regex misbehaves, check if your special characters need escaping — dots, brackets, and slashes often do.

Ask Codex about Regex →
⚡ DEV INTEL Tools & Severity
🟢 Low ⚙ Fix effort: Low
⚡ Quick Fix
Use named captures (?P<year>\d{4}) instead of numbered ones — $matches['year'] is self-documenting and doesn't break when you add new groups before it
📦 Applies To
PHP 5.3+ any web cli queue-worker
🔗 Prerequisites
🔍 Detection Hints
$matches[1] $matches[2] accessing captures by index; adding new group before existing group breaking all downstream index references
Auto-detectable: ✗ No phpstan phpcs
⚠ Related Problems
🤖 AI Agent
Confidence: Low False Positives: High ✓ Auto-fixable Fix: Low Context: Line


✓ schema.org compliant