我有一个输出两个单词的变量。我需要一种方法将这些数据分成两个单独的单词,并为每个单独的单词指定一个新变量。例如:
$request->post['colors']
如果输出是字符串"blue green"
,我需要将这两种颜色分成单独的变量,一个用于蓝色,另一个用于绿色,
...例如$color_one
代表蓝色,$color_two
代表green
。
答案 0 :(得分: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']);
答案 1 :(得分: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..