2017-07-04 121 views
1

任何人都可以幫助這個正則表達式嗎?如何將分隔字符串轉換爲帶關聯鍵的多維數組?

這裏是一個示例字符串,我試圖轉換成php數組。

$str="hopOptions:hops hopOptions:salmonSafe region:domestic region:specialty region:imported"

我需要最終阿雷是:

$filters = array (
    "hopOptions" => array("hops", "salmonSafe"), 
    "region"  => array("domestic", "specialty", "imported") 
); 

任何幫助或方向將不勝感激!

回答

0

更快的是避免正則表達式,並使用兩個爆炸電話:

Demo

代碼:

$str = "hopOptions:hops hopOptions:salmonSafe region:domestic region:specialty region:imported"; 
foreach(explode(' ',$str) as $pair){ 
    $x=explode(':',$pair); 
    $result[$x[0]][]=$x[1]; 
} 
var_export($result); 

或用正則表達式...

PHP Demo

代碼:

$str = "hopOptions:hops hopOptions:salmonSafe region:domestic region:specialty region:imported"; 
if(preg_match_all('/([^ ]+):([^ ]+)/',$str,$out)){ 
    foreach($out[1] as $i=>$v){ 
     $result[$v][]=$out[2][$i]; 
    } 
    var_export($result); 
}else{ 
    echo "no matches"; 
} 
+0

@VadimGoncharov有沒有在你的價值觀的任何空間的可能性大嗎?這將是您的問題的相關信息。 – mickmackusa

+0

是的,字符串中的項目將被一個空格分隔,但這是空格。 –

+0

我會選擇這個作爲答案,因爲它使用正則表達式。但我意識到我可以使用php數組函數來獲得類似的結果。謝謝@mickamackusa –

0

我不知道PHP和想出這個。希望有更好的辦法。

$str = "hopOptions:hops hopOptions:salmonSafe region:domestic region:specialty region:imported"; 

// it creates an array of pairs 
$ta = array_map(function($s) {return explode(":", $s);}, explode(" ", $str)); 

// this loop converts the paris into desired form 
$filters = array(); 
foreach($ta as $pair) { 
    if (array_key_exists($pair[0], $filters)) { 
     array_push($filters[$pair[0]], $pair[1]); 
    } 
    else { 
     $filters[$pair[0]] = array($pair[1]); 
    } 
} 

print_r($filters); 

輸出:

Array 
(
    [hopOptions] => Array 
     (
      [0] => hops 
      [1] => salmonSafe 
     ) 

    [region] => Array 
     (
      [0] => domestic 
      [1] => specialty 
      [2] => imported 
     ) 

) 
相關問題