Reputation: 11
The echo $line_of_text;
gives me "test1 test2 test1 test2 "
But once I use the explode
by ' '
it only divides the string by 2 parts.
as a result it says pieces[0] = test1test1
and pieces[1]=test2test2
. I need it to be divided into 4. Thanks in regards.
UPDATE: I found the problem. The function seemed to be in a foreach
loop. It ran twice. I found out about it when I ran echo $pieces[0].'<br>';
. It gave me:
Test1 test2
Test1 test2
After some fixing I got it to work as I intended. Thanks for the quick responses.
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;
}
Upvotes: 0
Views: 821
Reputation: 9420
Use this to explode by any space or tab or by more spaces or tabs:
$pieces = preg_split('/\s+/u', trim($line_of_text));
print_r($pieces);
//Array ( [0] => test1 [1] => test2 [2] => test1 [3] => test2 )
Upvotes: 1
Reputation: 2663
I'm pretty sure the error is happening before. Can you share more of your code? When I try this
$line_of_text = "test1 test2 test1 test2 ";
$pieces = explode(' ', $line_of_text);
var_dump($pieces);
It gives me the output
array(5) {
[0]=>
string(5) "test1"
[1]=>
string(5) "test2"
[2]=>
string(5) "test1"
[3]=>
string(5) "test2"
[4]=>
string(0) ""
}
which is correct.
You can try out small snippets like this in an online interpreter, for example here: http://sandbox.onlinephpfunctions.com/
Upvotes: 0