douzi8548 2011-03-22 11:59
浏览 77
已采纳

Regex PCRE PHP preg_match_all:如何删除匹配数组中的空节点?

$text = 'Lorem Ipsum';
$re = '/(?<AA>Any)|(?<BB>Lorem)/ui';
$nMatches = preg_match_all($re, $text, $aMatches);

$aMatches will contain the following:

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

Question: Is it possible to return the array without nodes for named parts that have no matches?

 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
            )
    )
  • 写回答

2条回答 默认 最新

  • doushangxianq07480 2011-03-22 14:29
    关注

    Specifically for regex, you can see @Stephan's answer. More generally, when just manipulating arrays, you can use a combination of array_map and array_filter to do that. array_filter without a callback will strip the values that evaluates to false (== false not === false, see empty).

    For a single-level array:

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

    For a 2D array:

    $clean_array = array_filter(array_map('array_filter', $array));
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置