PHP - split String in Key/Value pairs

自古美人都是妖i 提交于 2019-11-26 08:27:30

问题


I have a string like this:

key=value, key2=value2

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

array(
  \"key\" => \"value\",
  \"key2\" => \"value2\"
)

I could do something like

$parts = explode(\",\", $string)
$parts = array_map(\"trim\", $parts);
foreach($parts as $currentPart)
{
    list($key, $value) = explode(\"=\", $currentPart);
    $keyValues[$key] = $value;
}

But this seems ridiciulous. There must be some way to do this smarter with PHP right?


回答1:


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



回答2:


<?php parse_str(str_replace(", ", "&", "key=value, key2=value2"), $array); ?>



回答3:


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




回答4:


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.



来源:https://stackoverflow.com/questions/4923951/php-split-string-in-key-value-pairs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!