2011-09-30 59 views
2

我想將通過逐行讀取文件返回的字符串傳遞給函數。但它的安息一個不尋常的錯誤。看起來好像返回的字符串不完全是.txt文件中的行(源文件)。但是,如果我手動將字符串通過粘貼複製粘貼到函數中,它可以工作。使用ma代碼: -在逐行讀取文件時返回的字符串

<?php 
function check($string) { // for removing certain text from the file 
$x = 0; 
$delete = array(); 
$delete[0] = "*"; 
$delete[1] = "/"; 
for($i=0;$i<2;$i++){ 
    $count=substr_count($string,$delete[$i]); 
if($count>0){ 
$x++; 
return false; 
break; 
} 
} 
if($x==0)return true; 
} 
$file = fopen("classlist.txt", "r") or die("Unable to open file!"); 
$myFile = "new.txt"; 
$fh = fopen($myFile, "w") or die("can't open file"); 
while(!feof($file)){ 
if(check(fgets($file))){ 
$stringData = fgets($file); 
fwrite($fh, $stringData); 
} 
} 
fclose($fh); 
?> 

我得到什麼馬new.txt文件是:2號線4號線6 line8 ----------線21 PLZ幫我了.....

回答

2

每個調用fgets()從文件中檢索一個新行。將其稱爲,每循環迭代一次,將返回的行放入變量中,然後檢查並使用該變量。

2

while循環看起來應該更像是這樣的:

while(!feof($file)){ 
    $stringData = fgets($file); 
    if(check($stringData)){ 
     fwrite($fh, $stringData); 
    } 
} 

因爲你調用與fgets兩次,你檢查奇數行和寫出偶數行。

0

您可以重寫代碼,以便減少可能發生錯誤的位置,SplFileObject可以方便地使用文本文件操作並遍歷每一行。

A FilterIterator可用於返回那些不包含*/的行。

實施例:

<?php 

$inFile = "classlist.txt"; 
$myFile = "new.txt"; 

$outFile = new SplFileObject($myFile, 'w'); 

class LineFilter extends FilterIterator 
{ 
    public function accept() 
    { 
     $line = $this->getInnerIterator()->current(); 
     return strlen($line) === strcspn($line, '*/'); 
    } 
} 

$filteredLines = new LineFilter(new SplFileObject($inFile)); 

foreach($filteredLines as $line) 
{ 
    $outFile->fwrite($line); 
} 

?>