PHP - 在键/值对中拆分字符串

2021-12-28 00:00:00 string split key-value php

我有一个这样的字符串:

I have a string like this:

键=值,键2=值2

我想把它解析成这样:

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

我可以做类似的事情

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

但这似乎很荒谬.一定有什么方法可以用 PHP 更聪明地做到这一点,对吗?

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

推荐答案

如果你不介意使用正则表达式 ...

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

相关文章