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 如何在node.js中或者java中给wav格式的音频编码成sil格式呢
  • ¥15 不小心不正规的开发公司导致不给我们y码,
  • ¥15 我的代码无法在vc++中运行呀,错误很多
  • ¥50 求一个win系统下运行的可自动抓取arm64架构deb安装包和其依赖包的软件。
  • ¥60 fail to initialize keyboard hotkeys through kernel.0000000000
  • ¥30 ppOCRLabel导出识别结果失败
  • ¥15 Centos7 / PETGEM
  • ¥15 csmar数据进行spss描述性统计分析
  • ¥15 各位请问平行检验趋势图这样要怎么调整?说标准差差异太大了
  • ¥15 delphi webbrowser组件网页下拉菜单自动选择问题