猿问

如何将此字符串转换为键值数组?

我有一个像下面这样的字符串,包括括号:

("string" "value" "string" "value" "string" "value" ...)

引用部分的数量是未知的,最少一对,我想把它变成一个关联数组,我想要的结果是:

array('string'=>$value,'string'=>$value, 'string'=>$value)

我怎么能这样做?最好,我想使用内置函数或单衬或创建自定义函数,任何帮助将不胜感激。


隔江千里
浏览 211回答 3
3回答

慕后森

如何使用内置函数:)$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);

白猪掌柜的

<?php$str='("foo" "bar" "ying" "yang" "apple" "orange")';$cols&nbsp; &nbsp; = str_getcsv(trim($str, '()'), ' ');$chunked = array_chunk($cols, 2);$result&nbsp; = array_column($chunked, 1, 0);var_dump($cols, $chunked, $result);输出:array(6) {&nbsp; &nbsp; [0]=>&nbsp; &nbsp; string(3) "foo"&nbsp; &nbsp; [1]=>&nbsp; &nbsp; string(3) "bar"&nbsp; &nbsp; [2]=>&nbsp; &nbsp; string(4) "ying"&nbsp; &nbsp; [3]=>&nbsp; &nbsp; string(4) "yang"&nbsp; &nbsp; [4]=>&nbsp; &nbsp; string(5) "apple"&nbsp; &nbsp; [5]=>&nbsp; &nbsp; string(6) "orange"&nbsp; }&nbsp; array(3) {&nbsp; &nbsp; [0]=>&nbsp; &nbsp; array(2) {&nbsp; &nbsp; &nbsp; [0]=>&nbsp; &nbsp; &nbsp; string(3) "foo"&nbsp; &nbsp; &nbsp; [1]=>&nbsp; &nbsp; &nbsp; string(3) "bar"&nbsp; &nbsp; }&nbsp; &nbsp; [1]=>&nbsp; &nbsp; array(2) {&nbsp; &nbsp; &nbsp; [0]=>&nbsp; &nbsp; &nbsp; string(4) "ying"&nbsp; &nbsp; &nbsp; [1]=>&nbsp; &nbsp; &nbsp; string(4) "yang"&nbsp; &nbsp; }&nbsp; &nbsp; [2]=>&nbsp; &nbsp; array(2) {&nbsp; &nbsp; &nbsp; [0]=>&nbsp; &nbsp; &nbsp; string(5) "apple"&nbsp; &nbsp; &nbsp; [1]=>&nbsp; &nbsp; &nbsp; string(6) "orange"&nbsp; &nbsp; }&nbsp; }&nbsp; array(3) {&nbsp; &nbsp; ["foo"]=>&nbsp; &nbsp; string(3) "bar"&nbsp; &nbsp; ["ying"]=>&nbsp; &nbsp; string(4) "yang"&nbsp; &nbsp; ["apple"]=>&nbsp; &nbsp; string(6) "orange"&nbsp; }

天涯尽头无女友

一种方法是匹配一对带引号的字符串的模式,然后使用匹配中的两个字符串在回调函数中填充结果数组。preg_replace_callback('/"([^"]+)" "([^"]+)"/', function($match) use (&$result) {&nbsp; &nbsp; $result[$match[1]] = $match[2];}, $str);
随时随地看视频慕课网APP
我要回答