How can I get only named captures from preg_match?

14,647

Solution 1

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

Solution 2

return array(
    'name' => $matches['name'],
    'likes' => $matches['likes'],
);

Some kind of filter, sure.

Share:
14,647
Aillyn
Author by

Aillyn

http://xkcd.com/162/

Updated on July 01, 2022

Comments

  • Aillyn
    Aillyn almost 2 years

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