1.2.749. Named Regex

Captured subpatterns may be named, for easier reference.

From the manual : It is possible to name a subpattern using the syntax (?P<name>pattern). This subpattern will then be indexed in the matches array by its normal numeric position and also by name. PHP 5.2.2 introduced two alternative syntaxes (?<name>pattern) and (?'name'pattern).

Naming subpatterns makes it easier to know what is read from the results of the subpattern : for example, $r['name'] has more meaning than $r[1].

Named subpatterns may also be shifted in the regex without impact on the resulting array.

<?php

$x = 'abc';
preg_match_all('/(?<name>a)/', $x, $r);
print_r($r[1]);
print_r($r['name']);

preg_match("/(?<name>a)(?'sub'b)/", $x, $s);
print $s[2];
print $s['sub'];

?>

See also Subpatterns.

1.2.749.1. Suggestions

  • Use named regex, and stop using integer-named subpatterns

1.2.749.2. Specs

Short name

Structures/NamedRegex

Rulesets

All, Suggestions

Exakat since

1.4.9

PHP Version

All

Severity

Time To Fix

Precision

High

Features

regex

Examples

Phinx, shopware

Available in

Entreprise Edition, Exakat Cloud