PHP - split String in Key/Value pairs

后端 未结 4 2031
春和景丽
春和景丽 2020-11-28 13:49

I have a string like this:

key=value, key2=value2

and I would like to parse it into something like this:

array(
         


        
相关标签:
4条回答
  • 2020-11-28 13:58

    If you don't mind using regex ...

    $str = "key=value, key2=value2";
    preg_match_all("/([^,= ]+)=([^,= ]+)/", $str, $r); 
    $result = array_combine($r[1], $r[2]);
    var_dump($result);
    
    0 讨论(0)
  • 2020-11-28 13:58
    <?php parse_str(str_replace(", ", "&", "key=value, key2=value2"), $array); ?>
    
    0 讨论(0)
  • 2020-11-28 14:11

    if you change your string to use & instead of , as the delimiter, you can use parse_str()

    0 讨论(0)
  • 2020-11-28 14:18

    If you can change the format of the string to conform to a URL query string (using & instead of ,, among other things, you can use parse_str. Be sure to use the two parameter option.

    0 讨论(0)
提交回复
热议问题