12

Possible Duplicate:
how to force preg_match preg_match_all to return only named parts of regex expression

I have this snippet:

$string = 'Hello, my name is Linda. I like Pepsi.';
$regex = '/name is (?<name>[^.]+)\..*?like (?<likes>[^.]+)/';

preg_match($regex, $string, $matches);

print_r($matches);

This prints:

Array
(
    [0] => name is Linda. I like Pepsi
    [name] => Linda
    [1] => Linda
    [likes] => Pepsi
    [2] => Pepsi
)

How can I get it to return just:

Array
(
    [name] => Linda
    [likes] => Pepsi
)

Without resorting to filtering of the result array:

foreach ($matches as $key => $value) {
    if (is_int($key)) 
        unset($matches[$key]);
}
Community
  • 1
  • 1
Aillyn
  • 23,354
  • 24
  • 59
  • 84
  • You can use [T-Regx](https://t-regx.github.io) library, and use `namedGroups()` method. – Danon Nov 01 '18 at 10:14

2 Answers2

11

preg_match will always return the numeric indexes regardless of named capturing groups

Scuzzy
  • 12,186
  • 1
  • 46
  • 46
2
return array(
    'name' => $matches['name'],
    'likes' => $matches['likes'],
);

Some kind of filter, sure.

Constantine
  • 119
  • 8
  • 7
    `foreach($matches as $k => $v) { if(is_int($k)) { unset($matches[$k]); } }` to strip numeric keys and keep only the named ones. – Radu Feb 04 '15 at 15:50
  • 4
    Nowadays (php 5.6+) `$matches = array_filter($matches, 'is_string', ARRAY_FILTER_USE_KEY);` is a simpler way to achieve the same. Apply 'is_string' as a filter on the keys. – kander May 15 '19 at 08:43