Valentin Tanasescu
Valentin Tanasescu

Reputation: 106

Return matches with preg_match without items with numerical keys

$str = 'foobar: 2008';

preg_match('/(?P<name>\w+): (?P<digit>\d+)/', $str, $matches);

print_r($matches);

Array
(
    [0] => foobar: 2008
    [name] => foobar
    [1] => foobar
    [digit] => 2008
    [2] => 2008
)

I want $matches to contain only 'name' and 'digit' values without deleting the others by iteration.

Is it any faster way? Can preg_match by default return for me only string-type keys ?

Note: the above preg_match is an example. I would like a solution for any inputs.

Upvotes: 3

Views: 779

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627082

There is no "simple" way as preg_match has no such an option to only output named groups.

If you must remove the items with numerical keys from the array and do not want to use explicit loops you may use this array_filter workaround:

$str = 'foobar: 2008';
if (preg_match('/(?P<name>\w+): (?P<digit>\d+)/', $str, $matches)) {
    print_r(
      array_filter($matches, function ($key) { return !is_int($key); }, ARRAY_FILTER_USE_KEY)
    );
} // => Array ( [name] => foobar [digit] => 2008 )

See the PHP demo

Upvotes: 3

Related Questions