我有一個字符串變量:將一個字符串轉換成數組鍵
$asd = '[asd] => 0, [mogh] => 1,[for] => 3 ';
我想將其轉換成與按鍵陣列。這就是我想要的:
$array['asd'] = 0
$array['mogh'] = 1
$array['for'] = 3
我有一個字符串變量:將一個字符串轉換成數組鍵
$asd = '[asd] => 0, [mogh] => 1,[for] => 3 ';
我想將其轉換成與按鍵陣列。這就是我想要的:
$array['asd'] = 0
$array['mogh'] = 1
$array['for'] = 3
,如果你正在構建這個,甚至var_export()
根據您的需求,您應該使用其他格式,如JSON但是如果你沒有選擇:
preg_match_all('/\[([^\]]+)\] => (\d+)/', $asd, $matches);
$array = array_combine($matches[1], $matches[2]);
或者你可以清理它並將它變成一個查詢字符串來解析:
echo $asd = str_replace(array('[',']',' ','=>',','), array('','','','=','&'), $asd);
parse_str($asd, $array);
至於你模仿查詢字符串解析的第二種方法:我們知道可能有一個數組像'ab [] = 1&ab [] = 2&...'這將被替換破壞。但當然,我的意見涉及一個更復雜的案例... – RomanPerekhrest
so [asd] => 0,[mogh] => 1,[for] => 3將會是asd = 0&mogh = 1&for = 3 –
是'ASD = 0&mogh = 1&爲= 3'。萊姆猜測,那是你真正想要的? – AbraCadaver
爲什麼?你在哪裏得到這個字符串? – AbraCadaver
字符串是固定格式嗎?使用json_decode並將字符串指定爲「$ asd ='{」asd「:0,」mogh「:1,」for「:3}';'然後,您只需調用json_decode( $ ASD,真正的); (第二個參數使它返回一個數組而不是一個對象) – Theo