[英]Loop through text file, amend & write new file PHP
我有一個名為test.txt
的文件。 它具有多行文本,如下所示:
Test Data:
Tester 2 Data:
Tests 3 Data:
我希望有一個PHP腳本來打開該文件,在每一行上的Data:
一詞之前刪除所有文本,並輸出結果:
Data:
Data:
Data:
到目前為止,我的PHP :
$myfile = fopen("test.txt", "r") or die("Unable to open file!");
$data = fread($myfile,filesize("test.txt"));
// foreach line do this
$line = strstr($data,"Data:");
//append $line to newtest.txt
// endforeach
fclose($myfile);
您可以使用file()
逐行打開和循環瀏覽文件。
當您刪除Data:
之前的所有內容時,根據您提供的測試數據(這是我要做的所有事情),我們只需要知道行數即可。 因此,我們可以使用count()
獲取該信息。
然后將新數據構造為變量,最后使用file_put_contents()
將變量寫入(新)文件。
使用trim()
將刪除最后一個額外的行返回。
$raw = file("./test.txt");
$lineCount = count($raw);
$newFile = null;
do {
$newFile .= "Data:\r\n";
} while(--$lineCount > 0);
file_put_contents('./test-new.txt',trim($newFile));
編輯:正如“ 不要驚慌 ”在下面的評論中所說,您可以使用str_repeat()
甚至刪除do while
循環。
這是count()
移動的版本:
$raw = file("./test.txt");
$newFile = str_repeat("Data:\r\n",count($raw));
file_put_contents('./test-new.txt',trim($newFile));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.