explode不适用于字符串

时间:2015-05-27 07:22:57

标签: php explode

echo $ line_of_text;给我" test1 test2 test1 test2" 但是,一旦我使用了“爆炸”。 '它只将字符串分成两部分。 结果它说片[0] = test1test1和pieces [1] = test2test2。我需要它将其分为4.感谢您。

更新:我发现了问题。该函数似乎在每个循环中。它跑了两次。当我运行echo $pieces[0].'<br>';时,我发现了它。它给了我:
Test1 test2
Test1 test2

经过一些修复后,我按照我的意图开始工作。感谢您的快速回复。

    public function load_time_period()
{
    $file_handle = fopen($GLOBALS['configfile_time_periods'], "r+");

    $i = -1;
    while (!feof($file_handle)) {

        $line_of_text = fgets($file_handle);

        switch ($line_of_text) {

            case stripos($line_of_text, "define timeperiod") > -1:
                if (stripos($line_of_text, "define timeperiod") > -1) {
                    $i++;
                    $obj_time_periods[$i] = new nagmon_time_period();
                }
                break;

            case stripos($line_of_text, "timeperiod_name") > -1:
                $obj_time_periods[$i]->set_timeperiod_name(trim(str_replace("#", "", str_replace("timeperiod_name", "", $line_of_text))));
                break;

            case stripos($line_of_text, "alias") > -1:
                $obj_time_periods[$i]->set_alias(trim(str_replace("#", "", str_replace("alias", "", $line_of_text))));
                break;

            case stripos($line_of_text, "weekday") > -1:
                $obj_time_periods[$i]->set_weekday(trim(str_replace("#", "", str_replace("[weekday]", "", $line_of_text))));
                break;

            case stripos($line_of_text, "exception") > -1:
                $obj_time_periods[$i]->set_exception(trim(str_replace("#", "", str_replace("[exception]", "", $line_of_text))));
                break;
            case stripos($line_of_text, "exclude") > -1:
                $obj_time_periods[$i]->set_exclude(trim(str_replace("#", "", str_replace("exclude", "", $line_of_text))));
                break;

            case stripos($line_of_text, " ") > -1:



                echo htmlentities($line_of_text);



                $obj_time_periods[$i]->set_variable_command($pieces[0]);
                $obj_time_periods[$i]->set_variable_value($pieces[1]);
                break;

            default:
                break;
        }
    }
    fclose($file_handle);
    return $obj_time_periods;


}

2 个答案:

答案 0 :(得分:1)

使用它可以通过任何空格或制表符或更多空格或标签进行爆炸:

$pieces = preg_split('/\s+/u', trim($line_of_text));
print_r($pieces);
//Array ( [0] => test1 [1] => test2 [2] => test1 [3] => test2 ) 

答案 1 :(得分:0)

我很确定错误发生在以前。你能分享更多的代码吗?我试试这个时

$line_of_text = "test1 test2 test1 test2 ";

$pieces = explode(' ', $line_of_text);
var_dump($pieces);

它给我输出

array(5) {
  [0]=>
  string(5) "test1"
  [1]=>
  string(5) "test2"
  [2]=>
  string(5) "test1"
  [3]=>
  string(5) "test2"
  [4]=>
  string(0) ""
}

这是正确的。

您可以在在线翻译中试用这样的小小片段,例如:http://sandbox.onlinephpfunctions.com/

enter image description here