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

在PHP中,用等号和逗号拆分字符串的最佳方法是什么,php,regex,string,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] =>

将以下字符串拆分为键值数组的最佳方法是什么

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

可以将
preg\u match\u 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

很容易理解explode是如何实现的

  <?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);
 ?>


现场演示:

explode在这里不起作用,因为地址字段也包含逗号