Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get only named captures from preg_match? [duplicate]

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]);
}
like image 488
Aillyn Avatar asked Nov 17 '11 21:11

Aillyn


1 Answers

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

like image 120
Scuzzy Avatar answered Sep 28 '22 01:09

Scuzzy