我有一个看起来像的字符串:
KEY1,"Value"KEY2,"Value"Key3,"Value"
这个字符串总是会变化,我需要一个关联数组的键/值的数量:
array (
'KEY1' => 'Value',
'KEY2' => 'Value',
'KEY3' => 'Value'
);
字符串中包含的数据,我认为正则表达式是最好的吗?
答案 0 :(得分:2)
假设您的值中不包含"
,则可以执行以下操作:
$str = 'KEY1,"Value1"KEY2,"Value2"Key3,"Value3"';
$pieces = preg_split('/(?<=[^,]")/',$str,-1,PREG_SPLIT_NO_EMPTY);
$result = array();
foreach($pieces as $piece) {
list($k,$v) = explode(",",trim$piece);
$result[$k] = trim($v,'"');
}
答案 1 :(得分:1)
php> $str = 'KEY1,"Value"KEY2,"Value"Key3,"Value"';
php> $hash = array();
php> preg_match_all("/(.*?),\"(.*?)\"/", $str, $m);
php> foreach($m[1] as $index => $key) {
... $hash[$key] = $m[2][$index];
... }
php> var_dump($hash);
array(3) {
["KEY1"]=>
string(5) "Value"
["KEY2"]=>
string(5) "Value"
["Key3"]=>
string(5) "Value"
}
答案 2 :(得分:0)
如果键在值之间发生变化,那么您将需要preg_split()。如果密钥总是相同的话,那么explode()应该是足够的。