拆分变量';将数据转换为单独的变量


Split Variable's Data Into Separate Variables

可能重复:
分成两个变量?

我有一个变量,它将输出两个单词。我需要一种方法将这些数据拆分为两个单独的单词,并为每个单独的单词指定一个新的变量。例如:

$request->post['colors']

如果输出是字符串"blue green",我需要将这两种颜色拆分为单独的变量,一个用于蓝色,另一个用于绿色,…例如$color_one用于蓝色$color_two用于green

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']);

您也可以使用带有爆炸的数组:

//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..