在PHP中,用等号和逗号分割字符串的最佳方法是什么

时间:2017-09-02 03:39:59

标签: php regex string

将以下字符串拆分为键值数组

的最佳方法是什么
$string = 'FullName=Thomas Marquez,Address=1234 Sample Rd, Apt 21, XX 33178,Age=37,Code=123';

预期产出

Array
    (
        [FullName] => Thomas Marquez
        [Address] => 1234 Sample Rd, Apt 21, XX 33178
        [Age] => 37
        [Code] => 123
    )

2 个答案:

答案 0 :(得分:3)

您可以将preg_match_all()与此正则表达式一起使用:

/([a-z]+)=([^=]+)(,|$)/i

<强>详情

/
([a-z]+)  match any letter 1 or more times (you can change it to \w if you need numbers
=         match a literal equal sign
([^=]+)   match anything but an equal sign, 1 or more times
(,|$)     match either a comma or the end of the string
/i        case-insensitive flag
像这样:

<?php
$string = "FullName=Thomas Marquez,Address=1234 Sample Rd, Apt 21, XX 33178,Age=37,Code=123";
preg_match_all("/([a-z]+)=([^=]+)(,|$)/i", $string, $m);
var_dump($m[1]); // keys
var_dump($m[2]); // values
var_dump(array_combine($m[1], $m[2])); // combined into one array as keys and values

答案 1 :(得分:3)

易于理解爆炸是如何做到的。

  <?php
     $string = 'FullName=Thomas Marquez,Address=1234 Sample Rd, Apt 21, XX 33178,Age=37,Code=123';

     $arr = explode(",", $string);
     $new = array();
     foreach($arr as $key=> $value){
       if (strpos($value,"=")){
          $value2 = explode("=", $value);
          $new[$value2[0]] = $value2[1];
          $prev = $value2[0];
      }else {
         $new[$prev] .= ",".$value;
      }
    }
 print_r($new);
 ?>

现场演示:https://eval.in/853961