2012-06-14 153 views
0

問題:爆炸串

我有一個字符串,它看起來像這樣:

[1=>2,3,4][5=>6,7,8][9=>10,11,12][13=>14,15][16=>17,18] 

問:

你怎麼能得到這個字符串進入這個?

1 
    2 
    3 
    4 
5 
    6 
    7 
    8 
9 
    10 
    11 
    12 
13 
    14 
    15 
16 
    17 
    18 
+0

您可以使用reg表達式和組 - 但正如Carsten所說,您到目前爲止嘗試了什麼? – BugFinder

+1

也許沒用:你好像試圖用一個自定義的格式來序列化一個數組,看看php的serialize()或者json_encode() – AsTeR

回答

1
$str = "[1=>2,3,4][5=>6,7,8][9=>10,11,12][13=>14,15][16=>17,18]"; 
$str = explode("]", $str); 
$finalResult = array(); 

foreach ($str as $element) { 
    if (!empty($element)) { 
     $element = substr($element, 1); 
     $element = explode("=>", $element); 

     // element[0] contains the key 
     $element[1] = explode(",", $element[1]); 
     $finalResult[$element[0]] = $element[1]; 
    } 
} 

print_r($finalResult); 
2

我會嘗試:

$input = '[1=>2,3,4][5=>6,7,8][9=>10,11,12][13=>14,15][16=>17,18]'; 
$output = array(); 

preg_match_all('\[(\d+)=>([\d,]+)\]', $input, $matches); 
foreach ($matches as $group) { 
    $output[$group[1])] = explode(',', $group[2]); 
} 

// and print result out: 

foreach ($output as $key => $val) { 
    echo $key . '<br/>'; 
    foreach ($val as $v) { 
    echo ' ' . $v . '<br/>'; 
    } 
} 
2

此代碼:

$input = '[1=>2,3,4][5=>6,7,8][9=>10,11,12][13=>14,15][16=>17,18]'; 
$regex = '~\[(?P<keys>\d)+=>(?P<values>(?:\d+,?)+)\]~'; 
$result = array(); 

if (preg_match_all($regex, $input, $matches)) { 
    foreach ($matches['keys'] as $key => $value) { 
    $result[$value] = explode(',', $matches['values'][$key]); 
    } 
} 

print_r($result); 

結果如下:

Array 
(
    [1] => Array 
     (
      [0] => 2 
      [1] => 3 
      [2] => 4 
     ) 

    [5] => Array 
     (
      [0] => 6 
      [1] => 7 
      [2] => 8 
     ) 

    [9] => Array 
     (
      [0] => 10 
      [1] => 11 
      [2] => 12 
     ) 

    [3] => Array 
     (
      [0] => 14 
      [1] => 15 
     ) 

    [6] => Array 
     (
      [0] => 17 
      [1] => 18 
     ) 

) 
1
<?php 
$str = "[1=>2,3,4][5=>6,7,8][9=>10,11,12][13=>14,15][16=>17,18]"; 
$parts1 = explode("][",$str); 

$parts1[0]=str_replace("[","",$parts1[0]); 
$parts1[count($parts1)-1]=str_replace("]","",$parts1[count($parts1)-1]); 

foreach($parts1 as $k=>$v){ 
    $parts2[]=explode("=>",$v); 
} 

foreach($parts2 as $k=>$v){ 
    echo "<div>".$v[0]."</div>"; 
    foreach(explode(",",$v[1]) as $key=>$value){ 
     echo "<div style='margin-left:20px'>".$value."</div>"; 
    } 
} 

產出將是 enter image description here

1

只有str_replace()使用:

$dict = array(
    '=>' => "\n\t", 
    ',' => "\n\t", 
    '][' => "\n", 
    '[' => '', 
    ']' => '', 
); 

echo str_replace(array_keys($dict), array_values($dict), $str); 

會給你想要的結果。

+0

謝謝你的解決方案,但是我犯了一個錯誤,沒有提到它應該在一個數組中。 – kexxcream