>我有一个名为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:rn";
} while(--$lineCount > 0);
file_put_contents('./test-new.txt',trim($newFile));
编辑: 正如Don't Panic在下面的评论中所说,您可以使用str_repeat()
甚至删除do while
循环。
这是count()
也内联移动的版本:
$raw = file("./test.txt");
$newFile = str_repeat("Data:rn",count($raw));
file_put_contents('./test-new.txt',trim($newFile));