我有一个这样的字符串:
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);
这篇关于PHP - 在键/值对中拆分字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!