PHP foreach爆炸

时间:2016-08-01 08:33:27

标签: php foreach explode

我是PHP的新手并试图找出为什么在第一行后我有' _'在输出的开头?

$myFile = fopen("sample.txt", "r");

while($strBuffer = fgets($myFile, 180)) {
$strExplode = explode(" ", $strBuffer);

foreach ($strExplode as $value) {
    echo $value . "_";
}

输出:

This_is_the_first_test_line.
_This_is_the_second_test_line.
_This_is_the_third_test_line._
编辑:我现在相信阵列中的最后一个元素' Line'正在存储换行符...导致它在新行上打印_

1 个答案:

答案 0 :(得分:0)

试试这个

$myFile = fopen("sample.txt", "r");

while($strBuffer = fgets($myFile)) {
  $temp= str_replace(" ","_", $strBuffer);
  echo $temp.'<br>';
}

如果要使用数组 试试这个

$myFile = fopen("sample.txt", "r");

 while($strBuffer = fgets($myFile)) {
     $strExplode = explode(" ", $strBuffer);

      foreach ($strExplode as $value) {
      if($value>"")
      echo $value . "_";
  }