2011-11-17 82 views
9

可能重复:
how to force preg_match preg_match_all to return only named parts of regex expression如何从preg_match获取命名捕获?

我有这样的片段:

$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 
) 

我怎么能GE t将其刚刚返回:

Array 
(
    [name] => Linda 
    [likes] => Pepsi 
) 

而不诉诸结果数组的过滤:

foreach ($matches as $key => $value) { 
    if (is_int($key)) 
     unset($matches[$key]); 
} 

回答

6

的preg_match将总是返回数值索引无论命名捕获组

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

某种类型的过滤器,肯定的。

+5

'的foreach { 如果(is_int($ k))的{ 未设置($比赛[$(为k $ => $ V $匹配) K]); } }'去掉数字键并保留唯一的名字。 – Radu