【问题标题】:PHP preg_split delimiter pattern, split at character chainPHP preg_split 分隔符模式,在字符链处拆分
【发布时间】:2013-02-23 07:45:35
【问题描述】:

使用以下字符串:

$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,'的子串?

提前致谢!

【问题讨论】:

标签: php design-patterns delimiter preg-split


【解决方案1】:

如果只能是,a,,a,,a,,那么这就够了:

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

【讨论】:

    【解决方案2】:

    看起来你实际上想要做的是分离出方括号的部分。你可以这样做:

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

    【讨论】:

    • 我测试了你的模式,应该改成:/(?&lt;=\])[^[]*(?=\[)/
    【解决方案3】:

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

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

    【讨论】:

      【解决方案4】:

      看看这段代码:

      $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"]
              )
      )
      

      【讨论】:

        猜你喜欢
        • 2019-07-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-06-11
        • 1970-01-01
        • 1970-01-01
        • 2023-04-02
        相关资源
        最近更新 更多