PHP-在键/值对中拆分字符串 [英] PHP - split String in Key/Value pairs

查看:66
本文介绍了PHP-在键/值对中拆分字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个像这样的字符串:

I have a string like this:

键=值,键2 =值2

key=value, key2=value2

,我想将其解析为这样的内容:

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

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-在键/值对中拆分字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆