Regexp提示请求

时间:2012-11-12 16:20:26

标签: php regex

我有一个像

这样的字符串
"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"
); 

但是下一步陷入困境

1 个答案:

答案 0 :(得分: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]);

将打印:

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

此处的关键不是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]);

打印:

Array
(
    [0] => first
    [1] => second[,b]
    [2] => third[a,b[1,2,3]]
    [3] => fourth[a[1,2]]
    [4] => sixth
    [5] => [s,[,e,[,v,],e,],n]
)
相关问题