[英]Convert a string to an associative array
您如何将这样的字符串转换为PHP中的关联数组?
key1="value" key2="2nd value" key3="3rd value"
You could use a regular expression to get the key/value pairs: 您可以使用正则表达式获取键/值对:
preg_match_all('/(\w+)="([^"]*)"/', $str, $matches);
But this would just get the complete key/value pairs. 但这只会得到完整的键/值对。 Invalid input like
key=value"
would not get recognized. A parser would do better. 无效的输入(例如
key=value"
将无法识别。解析器会做得更好。
EDIT: Gumbo's answer is a better solution to this. 编辑:Gumbo的答案是对此更好的解决方案。
This any good to you? 这对你有好处吗?
Assume your string is in a variable like this: 假设您的字符串在这样的变量中:
$string = 'key1="value" key2="2nd value" key3="3rd value"';
First: 第一:
$array = explode('" ', $string);
you now have 你现在有
array(0 => 'key1="value', 1=>'key2="2nd value', 2=>'key3="3rd value');
Then: 然后:
$result = array();
foreach ($array as $chunk) {
$chunk = explode('="', $chunk);
$result[$chunk[0]] = $chunk[1];
}
Using the regular expression suggested by Gumbo I came up with the following for converting the given string to an associative array: 使用Gumbo建议的正则表达式,我想到了以下将给定字符串转换为关联数组的方法:
$s = 'key1="value" key2="2nd value" key3="3rd value"';
$n = preg_match_all('/(\w+)="([^"]*)"/', $s, $matches);
for($i=0; $i<$n; $i++)
{
$params[$matches[1][$i]] = $matches[2][$i];
}
I was wondering if you had any comments. 我想知道您是否有任何评论。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.