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

查看:27
本文介绍了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);

这篇关于PHP - 在键/值对中拆分字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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