2016-08-01 167 views
-1

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

$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._ 

编辑:我现在相信,在数组“行”的最后一个元素是存储换行符..使其打印_在新行

+1

恩,因为你输出每个回声'_'? – Epodax

+0

但只有当Foreach循环运行时。当IE移动到一个新行时,为什么有一个_首先被打印? – NZSteve

+0

源文件中是否会出现空白行,然后会留下单个下划线? – RamRaider

回答

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 . "_"; 
    } 
+0

谢谢,我试图用一个数组将单词拆分成单独的元素..(但你的解决方案也工作:)) – NZSteve

+0

我更新我的文章 – paranoid

+0

没有运气那里。 – NZSteve