PHP - split String in Key/Value pairs
if you change your string to use &
instead of ,
as the delimiter, you can use parse_str()
<?php parse_str(str_replace(", ", "&", "key=value, key2=value2"), $array); ?>
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);
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.