0

我有一个字符串

"first,second[,b],third[a,b[1,2,3]],fourth[a[1,2]],sixth"

我想把它爆炸成数组

Array (
    0 => "first",
    1 => "second[,b]",
    2 => "third[a,b[1,2,3]]",
    3 => "fourth[a[1,2]]",
    4 => "sixth"
}

我试图删除括号:

preg_replace("/[ ( (?>[^[]]+) | (?R) )* ]/xis", 
             "",
             "first,second[,b],third[a,b[1,2,3]],fourth[a[1,2]],sixth"
); 

但是在下一步被卡住了

4

1 回答 1

4

PHP 的正则表达式支持递归模式,所以这样的东西可以工作:

$text = "first,second[,b],third[a,b[1,2,3]],fourth[a[1,2]],sixth";

preg_match_all('/[^,\[\]]+(\[([^\[\]]|(?1))*])?/', $text, $matches);

print_r($matches[0]);

这将打印:

大批
(
    [0] => 第一个
    [1] => 秒[,b]
    [2] => 第三[a,b[1,2,3]]
    [3] => 第四[a[1,2]]
    [4] => 第六
)

这里的关键不是split,而是match

您是否想在代码库中添加这样一个神秘的正则表达式,取决于您:)

编辑

我刚刚意识到我上面的建议与以 . 开头的条目不匹配[。为此,请这样做:

$text = "first,second[,b],third[a,b[1,2,3]],fourth[a[1,2]],sixth,[s,[,e,[,v,],e,],n]";

preg_match_all("/
    (             # start match group 1
      [^,\[\]]    #   any char other than a comma or square bracket
      |           #   OR
      \[          #   an opening square bracket
      (           #   start match group 2
        [^\[\]]   #     any char other than a square bracket
        |         #     OR
        (?R)      #     recursively match the entire pattern
      )*          #   end match group 2, and repeat it zero or more times
      ]           #   an closing square bracket
    )+            # end match group 1, and repeat it once or more times
    /x", 
    $text, 
    $matches
);

print_r($matches[0]);

打印:

大批
(
    [0] => 第一个
    [1] => 秒[,b]
    [2] => 第三[a,b[1,2,3]]
    [3] => 第四[a[1,2]]
    [4] => 第六
    [5] => [s,[,e,[,v,],e,],n]
)
于 2012-11-12T16:48:54.700 回答