【问题标题】:Regex PRCE PHP preg_match_all: How do remove empty nodes in matches array?Regex PCRE PHP preg_match_all:如何删除匹配数组中的空节点?
【发布时间】:2011-07-20 10:27:11
【问题描述】:
$text = 'Lorem Ipsum';
$re = '/(?<AA>Any)|(?<BB>Lorem)/ui';
$nMatches = preg_match_all($re, $text, $aMatches);

$aMatches 将包含以下内容:

Array (
    [0] => Array (
            [0] => Lorem
        )

    [AA] => Array (       //  do not include to result matches array
            [0] =>        //  because have not match for this part
        )

    [1] => Array (
            [0] => 
        )

    [BB] => Array (
            [0] => Lorem
        )

    [2] => Array (
            [0] => Lorem
        )
)

问题: 对于没有匹配的命名部分,是否可以返回没有节点的数组?

 Array (
        [0] => Array (
                [0] => Lorem
            )

        {there was [AA] && [1], but have not returned because empty} 

        [BB] => Array (
                [0] => Lorem
            )

        [1] => Array (        // changed to 1
                [0] => Lorem
            )
    )

【问题讨论】:

  • 你至少可以用$aMatches = array_filter($aMatches);清理它们
  • 如果不返回正则表达式会更好。从结果数组中删除并不困难,但如果空节点不来自正则表达式会更好。
  • 他们有不同的名字有什么原因吗?
  • @salathe:是的,这个正则表达式非常简化。实际上,我正在使用更多的命名组。

标签: php regex arrays pcre preg-match-all


【解决方案1】:

您可以通过使用分支重置运算符来实现类似的效果:

/(?|(?&lt;BB&gt;Any)|(?&lt;BB&gt;Lorem))/ui

输出

  • [0]=> 数组
    • [0]=>洛雷姆
  • [BB]=> 数组
    • [0]=>洛雷姆
  • [1]=> 数组
    • [0]=>洛雷姆

通过使用此运算符,命名组必须具有相同的名称。

您测试正则表达式here

【讨论】:

  • 感谢您的回答,但“没有匹配的命名部分的节点”的意思是,如果部分匹配,则必须将它们与您的姓名一起返回到数组。这是问题。只需要删除不匹配的部分。所有其他部分都必须留下他们的名字。
  • 那么你试过 array_filter 了吗?
【解决方案2】:

特别是正则表达式,你可以看到@Stephan's answer。更一般地,当仅操作数组时,您可以使用array_maparray_filter 的组合来执行此操作。没有回调的array_filter 将删除计算结果为false 的值(== false 不是=== false,请参阅empty)。

对于单级数组:

$array = array('foo', '', 'bar');
$clean_array = array_filter($array);

对于二维数组:

$clean_array = array_filter(array_map('array_filter', $array));

【讨论】:

  • !!!!!!!!!! This answer does not solve to answer, but is much closer to solution, because how I understand It is not possible solve with regex.
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-10-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多