不要保存索引捕获的组,只保存命名组

时间:2013-10-28 11:59:55

标签: php regex preg-match

我正在使用命名捕获组进行preg_match。当我打印出$matches时,它显示了命名组,但也显示了默认的索引组,如下所示:

Array
(
    [0] => placeholder/placeholder2
    [p1] => placeholder  <-- Named, good
    [1] => placeholder   <-- Indexed, don't want this
    [p2] => placeholder2 <-- Named, good
    [2] => placeholder2  <-- Indexed, don't want this
)

使用这段代码:

$str = 'placeholder/placeholder2';

preg_match('#(?P<p1>[[:alnum:]]+)/(?P<p2>[[:alnum:]]+)#', $str, $matches);

echo '<pre>';
print_r($matches);
echo '</pre>';

Demo available here

我只希望在$matches结果中包含已命名的组。如何避免将匹配保存为索引组?

1 个答案:

答案 0 :(得分:1)

使用preg_match()本身是不可能的 - 因为它实现了PCRE,PCRE无法做到这一点。

最简单的方法就是处理输出数组:

foreach($matches as $key=>$match)
{
   if(is_int($key))
   {
      unset($matches[$key]);
   }
}
相关问题