/J (Duplicate Named Groups)
What is /J (Duplicate Named Groups)?
/J (Duplicate Named Groups): Allows multiple capture groups in the same pattern to share the same name — normally a compile-time error. The J modifier in PHP's PCRE lets two capture groups in the same pattern share a name. Normally that is an error, because the engine cannot tell which group you mean. It is useful when a pattern has alternatives that capture the same thing in different ways. Think of a date that may be written as 2026-11-25 or 25/11/2026. With J, both branches can capture (?<year>...), and your code reads $m['year'] without caring which format matched.
Frequently asked questions about /J (Duplicate Named Groups)
What should you keep in mind with /J (Duplicate Named Groups)?
PCRE also offers (?|...), a branch reset group, which solves a similar problem with numbered groups. Both make the calling code simpler and the pattern harder to read. If a regex needs this much structure, consider splitting it into two simple patterns tried one after the other. That is usually easier to test and to explain to the next developer.
At a glance
| Category | Regex flags |
|---|---|
| Explained by | Reinier de la Parra |
| Updated |