2015-04-02 133 views
-4

我有這個字符串PHP:字符串轉換爲數組

[1: boy, 2: girl] 

我想將其轉換爲一個數組

1=>boy 
2=>girl 
+3

您是否嘗試過的東西? – Rizier123 2015-04-02 10:49:43

+0

我試過爆炸(),但它太複雜了 – 2015-04-02 10:56:01

+2

如果你谷歌「PHP字符串數組」,你會從字面上找到你的問題的數百個答案。 – 2015-04-02 10:56:05

回答

1

嗨,你可以使用爆炸辦得到所需的輸出

$tp = '[1: boy, 2: girl]'; 
$tp = trim($tp,'[]'); 
$new = array(); 
foreach(explode(',',$tp) as $each_elem){ 
    $temp = explode(':',$each_elem); 
    $new[trim($temp[0])] = $temp[1]; 
} 
1

試試這個:

$str = "[5: boy, 8: girl]"; 
$exps = preg_split('/\W/',$str, 0,PREG_SPLIT_NO_EMPTY); 
$size = count($exps); 
for($i=0; $i<$size; $i++) 
    $array[$exps[$i]] = $exps[++$i]; 

出來放:

5=>boy 
8=>girl 
0

簡單的正則表達式的解決方案:

preg_match_all('/(\d+): ([^,\]]+)/', $string, $matches); 
$array = array_combine($matches[1], $matches[2]);