3 回答
TA贡献1802条经验 获得超5个赞
如何使用内置函数:)
$str = '("string" "value" "string1" "value1" "string2" "value2")';
$str = preg_replace('~^\("|"\)$~', '', $str);
$ar = explode('" "', $str);
$ar = array_chunk($ar,2);
$ar = array_column($ar, 1, 0);
print_r($ar);
TA贡献1893条经验 获得超10个赞
<?php
$str='("foo" "bar" "ying" "yang" "apple" "orange")';
$cols = str_getcsv(trim($str, '()'), ' ');
$chunked = array_chunk($cols, 2);
$result = array_column($chunked, 1, 0);
var_dump($cols, $chunked, $result);
输出:
array(6) {
[0]=>
string(3) "foo"
[1]=>
string(3) "bar"
[2]=>
string(4) "ying"
[3]=>
string(4) "yang"
[4]=>
string(5) "apple"
[5]=>
string(6) "orange"
}
array(3) {
[0]=>
array(2) {
[0]=>
string(3) "foo"
[1]=>
string(3) "bar"
}
[1]=>
array(2) {
[0]=>
string(4) "ying"
[1]=>
string(4) "yang"
}
[2]=>
array(2) {
[0]=>
string(5) "apple"
[1]=>
string(6) "orange"
}
}
array(3) {
["foo"]=>
string(3) "bar"
["ying"]=>
string(4) "yang"
["apple"]=>
string(6) "orange"
}
TA贡献1831条经验 获得超9个赞
一种方法是匹配一对带引号的字符串的模式,然后使用匹配中的两个字符串在回调函数中填充结果数组。
preg_replace_callback('/"([^"]+)" "([^"]+)"/', function($match) use (&$result) {
$result[$match[1]] = $match[2];
}, $str);
- 3 回答
- 0 关注
- 210 浏览
添加回答
举报