可能重复:
how to force preg_match preg_match_all to return only named parts of regex expression
我有这个片段:
$string = 'Hello, my name is Linda. I like Pepsi.';
$regex = '/name is (?<name>[^.]+)\..*?like (?<likes>[^.]+)/';
preg_match($regex, $string, $matches);
print_r($matches);
打印:
Array
(
[0] => name is Linda. I like Pepsi
[name] => Linda
[1] => Linda
[likes] => Pepsi
[2] => Pepsi
)
我怎样才能让它返回:
Array
(
[name] => Linda
[likes] => Pepsi
)
无需过滤结果数组:
foreach ($matches as $key => $value) {
if (is_int($key))
unset($matches[$key]);
}
答案 0 :(得分:8)
preg_match将始终返回数字索引
答案 1 :(得分:2)
return array(
'name' => $matches['name'],
'likes' => $matches['likes'],
);
某种过滤器,当然。