我如何才能从preg_match中获取指定的捕获?(复制)

时间:2021-09-09 20:13:17

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

可能的重复:如何强制preg_match preg_match_all只返回regex表达式中指定的部分

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

2 个解决方案

#1


7  

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

preg_match将始终返回数字索引,而不考虑命名捕获组

#2


3  

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

Some kind of filter, sure.

当然是某种过滤器。

#1


7  

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

preg_match将始终返回数字索引,而不考虑命名捕获组

#2


3  

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

Some kind of filter, sure.

当然是某种过滤器。