将逗号分隔的 key=value 表达式字符串转换为关联数组
我有一个像这样的字符串:
key=value, key2=value2
我想将它解析成这样的东西:
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 更智能地做到这一点,对吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
如果您不介意使用正则表达式...
If you don't mind using regex ...
如果您将字符串更改为使用
&
而不是,
作为分隔符,则可以使用parse_str()
if you change your string to use
&
instead of,
as the delimiter, you can useparse_str()
如果您可以更改字符串的格式以符合 URL 查询字符串(使用
&
而不是,
等,您可以使用parse_str< /code>. 请务必使用两个参数选项。
If you can change the format of the string to conform to a URL query string (using
&
instead of,
, among other things, you can useparse_str
. Be sure to use the two parameter option.以下是使用
array_reduce
的单个命令解决方案,其格式为多行以提高可读性:Here's a single command solution using
array_reduce
formatted in multple lines for readability:为了涵盖此问题中未表达但由此页面关闭的页面表达的边缘情况,您可能需要允许 key=value 表达式分隔字符成为值的一部分(例如空格和逗号)。在这种情况下,使用否定先行来确保匹配的值实际上不是下一个键值表达式的一部分,并使用先行来匹配分隔字符或字符串结尾。
代码:(演示)
输出:
To cover a fringe case not expressed in this question, but expressed by a page closed by this page, you may need to allow key=value expression-separating characters to be part of the values (such as spaces and commas). In this case, use negated lookaheads to ensure the matched value is not actually part of the next key-value expression and use a lookahead to match the delimiting character(s) or the end of the string.
Code: (Demo)
Output: