【问题标题】:PHP split string into two arrays - values split and delimitersPHP 将字符串拆分为两个数组 - 值拆分和分隔符
【发布时间】:2014-01-08 20:53:53
【问题描述】:

我想拆分一个字符串,最有可能使用explode 或preg_split 来创建两个数组。第一个是分裂的。秒是分隔符。仅有的两个分隔符是“AND”或“OR”。

例如:

$string = "Name=John AND St​​ate=GA OR State=CA";

我不仅要捕获“Name=John,State=GA,State=CA”,还要捕获每个之间的分隔符。

对于这个例子,两个单独的数组是:

array (
        [0] => Name=John
        [1] => State=GA
        [2] => State=CA   
)

array (
        [0] => AND
        [1] => OR
)

从这里我可以按摩数据以符合我想要的,最后构建一个查询。如果有更好的方法来解决这个问题,我会全力以赴。感谢您的所有帮助!

【问题讨论】:

    标签: php explode preg-split


    【解决方案1】:

    使用 PHP Regular Expressionpreg_match_all() 您的情况下的函数:

    Live Demo

    代码:

    $input = "Name=John AND State=GA OR State=CA";
    
    preg_match_all("/[a-zA-Z]+\s*=\s*[a-zA-Z]+/", $input, $output_1);
    $output_1 = $output_1[0];
    
    
    preg_match_all("/AND|OR/", $input, $output_2);
    $output_2 = $output_2[0];
    
    print_r($output_1);
    print_r($output_2);
    

    输出:

    Array
    (
        [0] => Name=John
        [1] => State=GA
        [2] => State=CA
    )
    Array
    (
        [0] => AND
        [1] => OR
    )
    

    【讨论】:

      【解决方案2】:

      如果该字符串中的所有其他部分都是分隔符 (AND|OR),则无需使用正则表达式。通过空格字符将该字符串分解为数组,然后将所有其他项选择到一个数组中,将其他项选择到另一个数组中。像这样:

      <?php
      $string = "Name=John AND State=GA OR State=CA";
      $a = explode(' ', $string);
      
      $foo = array();
      $bar = array();
      $len = count($a);
      
      for($i = 0; $i < $len; $i++) {
          if($i % 2 === 0) {
              $foo[] = $a[$i];
          }
          else {
              $bar[] = $a[$i];
          }
      }
      
      print_r($foo);
      print_r($bar);
      

      https://eval.in/87538

      如果该字符串中的项目数量始终相同,则无需循环遍历它,只需将项目 0、2 和 4 分配给一个数组,将 1 和 3 分配给另一个数组。

      【讨论】:

      • 感谢您的评论。这实际上是我在发布之前最初对其进行编码的方式(实际上是在空格上进行了 preg_split,但与 % 2 的概念相同)。问题是'Name = John'之间可以选择空格。可能是“姓名=约翰”、“姓名=约翰”等。不过,感谢您的回复。上面的答案效果很好,所以我会接受它。
      【解决方案3】:

      state 值很有可能是OregonOR),这意味着@rullof 的答案不可靠。

      通过在输入字符串的单次传递中使用值,可以稳定任务。

      这两个组可以通过array_column()提取。

      代码:(Demo)

      $string = "Name=John AND State=OR OR State=CA";
      
      if (preg_match_all(
              '~([a-zA-Z]+=\S+)(?: ([A-Z]{2,3}))?~',
              $string,
              $out,
              PREG_SET_ORDER
          )
      ) {
          echo "data = ";
          var_export(array_column($out, 1));
          echo "\nconjunctions = ";
          var_export(array_column($out, 2));
      }
      

      输出:

      data = array (
        0 => 'Name=John',
        1 => 'State=OR',
        2 => 'State=CA',
      )
      conjunctions = array (
        0 => 'AND',
        1 => 'OR',
      )
      

      【讨论】:

        猜你喜欢
        • 2018-01-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多