2016-08-01 166 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