【问题标题】:Multiple matches of the same type in preg_matchpreg_match 中相同类型的多个匹配项
【发布时间】:2010-12-15 18:15:32
【问题描述】:

我想使用 preg_match 为带括号的子模式返回每个匹配项的数组。

我有这个代码:

    $input = '[one][two][three]';

    if ( preg_match('/(\[[a-z0-9]+\])+/i', $input, $matches) )
    {
        print_r($matches);
    }

打印出来:

Array ( [0] => [one][two][three], [1] => [three] ) 

... 只返回完整的字符串和最后一个匹配项。我希望它返回:

Array ( [0] => [one][two][three], [1] => [one], [2] => [two], [3] => [three] ) 

这可以用 preg_match 完成吗?

【问题讨论】:

    标签: php regex preg-match


    【解决方案1】:

    使用 preg_match_all() 并删除 +

    $input = '[one][two][three]';
    
    if (preg_match_all('/(\[[a-z0-9]+\])/i', $input, $matches)) {
        print_r($matches);
    }
    

    给予:

    Array
    (
        [0] => Array
            (
                [0] => [one]
                [1] => [two]
                [2] => [three]
            ),
    
        [1] => Array
            (
                [0] => [one]
                [1] => [two]
                [2] => [three]
            )
    )
    

    【讨论】:

      【解决方案2】:
      $input = '[one][two][three]';
      
      if ( preg_match_all('/(\[[a-z0-9]+\])+/iU', $input, $matches) )
      {
          print_r($matches);
      }
      

      【讨论】:

        猜你喜欢
        • 2010-12-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-06-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多