2011-12-18 39 views
1

我想閱讀PHP中匹配條件後中斷或退出的文本文件。PHP讀取文本文件,直到匹配條件時中斷

PHP代碼:

$file = fopen("testFile.txt", "r") or exit("Unable to open file!"); 
//Output a line of the file until the end is reached 
while(!feof($file)) 
{ 

    $line = fgets($file, 1024); 
    if($line=="NOTE"){ 
     break; 
    } 
    echo $line ."<br>"; 

} 
fclose($file); 

line1: i love u so much 
line2: this is tom 
Line3: note 
Line: this is jam 

結果需要:

當滿足說明會中斷。

line1: i love u so much 
line2: this is tom 
+0

你會得到什麼輸出?你期望得到什麼輸出?該文件如何查看? – MeLight 2011-12-18 09:10:11

+0

例 行1:我愛你那麼多 線路2:這是湯姆 3號線:注意 線:這是果醬 結果需要: 當滿足說明會中斷。 line1:我很愛你 line2:這是tom – 2011-12-18 09:14:43

+0

第3行'note'或者'NOTE'? – 2011-12-18 09:17:11

回答

1

從我收集你可以有不同的情況,像馬里奧說你也有endlines。你應該這樣檢查:

if(strtolower(trim($line)) == "note"){ 
    break; 
} 
1

fgets()獲得該行仍包括結尾的新行。所以,你要麼必須要檢查的修剪線:

if (trim($line) == "NOTE") 

或者,如果你有一定的斷行變種(\ n或\ r \ n)的確切行:

if ($line == "NOTE\r\n") { 

其他備選包括strncmp()如果你只想檢查註釋行的開始,或者如果你想檢查行中某處的存在,則使用strstr()或strpos()。

+0

也.. ..大小寫敏感應該照顧 – 2011-12-18 09:16:43

+0

非常感謝它的工作。 – 2011-12-18 09:20:01

+0

編輯之後不確定問題是什麼了。但是strtolower(),strncasecmp(),stristr()或stripos()會成爲下一個選擇。 – mario 2011-12-18 09:20:06

0

我建議file_get_contents

$sFile = file_get_contents("testFile.txt") or die("Unable to open file!"); 
$sFile = preg_replace(array("/\r\n/", "/\r/", "/\n/"), "<br />", $sFile); //array because of some fixes 
$sFile = preg_replace("/<br \/>(\s+)?Note(\s+)?(<br \/>.+|$)/i", "<br />", $sFile); 
echo $sFile;