I have a string that looks like:
我有一个看起来像这样的字符串:
KEY1,"Value"KEY2,"Value"Key3,"Value"
This string will always vary in the number of keys/values i need an associative array:
这个字符串总是在我需要一个关联数组的键/值的数量上有所不同:
array (
'KEY1' => 'Value',
'KEY2' => 'Value',
'KEY3' => 'Value'
);
of the data contained in the string, a regular expression would be best I suppose?
对于字符串中包含的数据,我认为正则表达式是最好的吗?
3 个解决方案
#1
2
Assuming your values don't contain a "
in them you can do:
假设您的值不包含“在其中,您可以执行以下操作:
$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,'"');
}
看到它在行动!
#2
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"
}
#3
0
If the key changes between values then you'll need preg_split(). If the key is always the same then explode() should be more than adequate.
如果键在值之间发生变化,那么您将需要preg_split()。如果密钥总是相同,那么explode()应该是足够的。
#1
2
Assuming your values don't contain a "
in them you can do:
假设您的值不包含“在其中,您可以执行以下操作:
$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,'"');
}
看到它在行动!
#2
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"
}
#3
0
If the key changes between values then you'll need preg_split(). If the key is always the same then explode() should be more than adequate.
如果键在值之间发生变化,那么您将需要preg_split()。如果密钥总是相同,那么explode()应该是足够的。