How to determine if PREG named groups were used in the template passed to preg_match ()?

I am interested in determining whether named groups were used in the template passed to preg_match ().

Imagine a scenario in which the list of regular expression patterns is repeated and passed to preg_match (). Something like the following:

$trg = "123abc/4";
$patterns = array('/abc/', '/abc\/(\d+)/', '/abc\/(?P<id>\d+)/');
foreach ($patterns as $p) {
   preg_match($p, $trg, $matches);
   if (len($matches) > 0) {
      // Do something interesting with the capture
   } 
}

If a match is found, then there will be at least one element in $ match. The last two templates contain a capture, but $ match will be an array of two elements in the first case and an array of three elements in the last.

I want to know without a grepping pattern if named groups have been used. I need to know this because I want to pass the captured text to other functions.

, , .

, ?

.

+3
4

is_assoc? PHP , .

<?php
function is_assoc(&$arr) {
    return array_keys($arr) !== range(0, count($arr) - 1);
}
if (preg_match('/(?P<foo>foo)/', 'foo', $match) && is_assoc($match)) {
    echo "yep, it had named groups";
}

"" PHP ( ), if - .

, , , , , , , , . foreach ($patterns as $p) foreach ($patterns as $i=>$p) $i, ?

0

, .


(
  [0] = > abc/4
  [id] = > 4
  [1] = > 4
)

0

, array_keys, , .

0

T-Regx Match:

$match->namedGroups();
0
source

Source: https://habr.com/ru/post/1779447/


All Articles