How can I get only named captures from preg_match?

Aillyn picture Aillyn · Nov 17, 2011 · Viewed 13.6k times · Source

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]);
}

Answer

Scuzzy picture Scuzzy · Nov 17, 2011

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