[英]PHP: from string to array: argument => parametr
I have got strings like: 我有这样的字符串:
name="n e" content="12" icon="favicon.ico"
What is the best and quickest way to parse it as such array: 解析它作为这样的数组的最佳和最快的方法是什么:
Array
(
[name] => "n e"
[content] => "12"
[icon] => "favicon.ico"
)
This should do it, using preg_match_all()
to get all the groups and array_combine()
to form the final array: 这应该这样做,使用preg_match_all()
获取所有组和array_combine()
以形成最终数组:
if (preg_match_all('/(\w+)="([^"]*)"/', $str, $matches)) {
return array_combine($matches[1], $matches[2]);
} else {
return array();
}
Edit 编辑
This alternative breaks when there are spaces in between the double quotes; 当双引号之间有空格时,这种替代方案会中断; otherwise it works as well: 否则它也有效:
parse_str(str_replace(array(' ', '"'), array('&', ''), $s), $a);
return $a;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.