PHP preg_split定界符模式,在字符链中拆分

时间:2013-03-07 21:58:47

标签: php design-patterns delimiter preg-split

使用以下字符串:

$str = '["one","two"],a,["three","four"],a,,a,["five","six"]';

preg_split( delimiter pattern, $str );

我如何设置分隔符模式以获得此结果:

$arr[0] = '["one","two"]';
$arr[1] = '["three","four"]';
$arr[2] = '["five","six"]';

换句话说,是否有一种方法可以分割模式',a,'AND',a,a,'但是检查',a,a,'首先因为',a,'是一个子串',a,a,'?

提前致谢!

4 个答案:

答案 0 :(得分:1)

看起来你真正要做的就是把方形括号部分分开。你可以这样做:

$arr = preg_split("/(?<=\])[^[]*(?=\[)/",$str);

答案 1 :(得分:1)

如果它只能是,a,,a,,a,,那么这应该足够了:

preg_split("/(,a,)+/", $str);

答案 2 :(得分:0)

如果你只想要括号之间的内容,我认为你应该使用preg_match而不是preg_split

  1. Extract whatever is in brackets using regular expressions
  2. php preg_split() to find text inbetween two words

答案 3 :(得分:0)

看看这段代码:

$result = array();

preg_match_all("/(\[[^\]]*\])/", '["one","two"],a,["three","four"],a,,a,["five","six"]', $result);

echo '<pre>' . print_r($result, true);

它将返回:

Array
(
    [0] => Array
        (
            [0] => ["one","two"]
            [1] => ["three","four"]
            [2] => ["five","six"]
        )

    [1] => Array
        (
            [0] => ["one","two"]
            [1] => ["three","four"]
            [2] => ["five","six"]
        )
)