2011-11-27 83 views
2

可能重複:
Split into two variables?拆分變量的數據爲獨立的變量

我有一個變量,將輸出兩個詞。我需要一種方法將這些數據分成兩個單獨的單詞,併爲每個分隔的單詞指定一個新變量。例如:

$request->post['colors'] 

如果輸出字符串"blue green",我需要這兩種顏色分成不同的變量,一個是藍色和一個用於綠色, ...如$color_one藍色$color_two的​​。

回答

6

explode()他們在空間和捕捉到的兩個結果與list()

list($color1, $color2) = explode(" ", $request->post['colors']); 
echo "Color1: $color1, Color2: $color2"; 

// If an unknown number are expected, trap it in an array variable instead 
// of capturing it with list() 
$colors = explode(" ", $request->post['colors']); 
echo $colors[0] . " " . $colors[1]; 

陣列組件如果你不能保證一個單一的空間將它們分開,使用preg_split()代替:

// If $request->post['colors'] has multiple spaces like "blue green" 
list($color1, $color2) = preg_split("/\s+/", $request->post['colors']); 
+0

這是一種享受!爲此非常感謝。另外,如果輸出是藍綠黃色(依此類推)呢?它會簡單地將變量的前兩個單詞? –

+0

你可以接受這樣的答案:http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work –

+0

@ASmith如果你不知道只會有兩個,不要'使用'list()'。而是捕獲一個數組變量。查看上面的更改。 –

3

您還可以使用一個爆炸陣:

//store your colors in a variable 
$colors=" blue green yellow pink purple "; 

//this will remove all the space chars from the end and the start of your string 
$colors=trim ($colors); 
$pieces = explode(" ", $colors); 
//store your colors in the array, each color is seperated by the space 

//if you don't know how many colors you have you can loop the with foreach 

$i=1; 
foreach ($pieces as $value) { 
    echo "Color number: ".$i." is: " .$value; 
    $i++; 

} 
//output: Color number: 1 is: blue 
//  Color number: 2 is: green etc.. 
+0

感謝您的大力幫助和建議。 –

+0

您好,我很樂意提供幫助 – Theodore