如何将字符串中的每个单词存储到特定变量中?

时间:2015-02-19 08:05:33

标签: php string split

请帮我把这些字符串放入一些特定的变量中。

$remove4 = "First 1st, Second 2nd, Third 3rd, Fourth 4th"; 

我正在使用此代码,但我可以正确使用它。谁能告诉我代码中的问题是什么?

    $str = (explode(",",$remove4));

$check = array();
for($i=0;$i<=$count;$i++){
    $check[] = $str[$i];
}

foreach($check as $value){
    echo $value . "<br>";
    $var=(explode(" ", $value));
        echo $var[0];
        echo $var[1];
}

目标:

Process1 = 'First';
Process2 = 'Second';
Process3 = 'Third';
Process4 = 'Fourth';

Temp1 = '1st';
Temp2 = '2nd';
Temp3 = '3rd';
Temp4 = '4th';

2 个答案:

答案 0 :(得分:1)

你可以试试这个

  foreach($check as $key => $value){
   //echo $value . "<br>";
    $var=(explode(" ", $value));
        ${'Process'.($key+1)} = $var[0];
        ${'Temp'.($key+1)} = $var[1];
}

echo $ Process1; echo $ Temp3;

答案 1 :(得分:1)

$remove4 = "First 1st, Second 2nd, Third 3rd, Fourth 4th";

$str = (explode(",",$remove4));

$check = array();


$i=0; foreach ($str as $value) { $i++;

    $explode = (array_values(array_filter(explode(" ",$value))));

    ${'Process'.($i)} = $explode[0];
    ${'Temp'.($i)} = $explode[1];
}

echo $Process1 . "<br /> ";
echo $Process2 . "<br /> ";
echo $Process3 . "<br /> ";
echo $Process4 . "<br /> ";

echo $Temp1 . "<br /> ";
echo $Temp2 . "<br /> ";
echo $Temp3 . "<br /> ";
echo $Temp4 . "<br /> ";

输出:

First
Second
Third
Fourth
1st
2nd
3rd
4th