如何使用PHP从文本文件的开头删除X行数? [英] How to use PHP to delete X number of lines from the beginning of a text file?
本文介绍了如何使用PHP从文本文件的开头删除X行数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在编写一个PHP脚本,该脚本会输出一个简单的文本文件日志,记录其执行的操作.当文件达到特定大小时,我将如何使用PHP从该文件中删除前几行?
I'm writing a PHP script and the script outputs a simple text file log of the operations it performs. How would I use PHP to delete the first several lines from this file when it reaches a certain file size?
理想情况下,我希望它保留前两行(创建的日期/时间和空白),并从第3行开始删除,并删除X行.我已经了解filesize()
函数,因此将使用它来检查文件大小.
Ideally, I would like it to keep the first two lines (date/time created and blank) and start deleting from line 3 and delete X amount of lines. I already know about the filesize()
function, so I'll be using that to check the file size.
示例日志文本:
*** LOG FILE CREATED ON 2008-10-18 AT 03:06:29 ***
2008-10-18 @ 03:06:29 CREATED: gallery/thumbs
2008-10-18 @ 03:08:03 RENAMED: gallery/IMG_9423.JPG to gallery/IMG_9423.jpg
2008-10-18 @ 03:08:03 RENAMED: gallery/IMG_9188.JPG to gallery/IMG_9188.jpg
2008-10-18 @ 03:08:03 RENAMED: gallery/IMG_9236.JPG to gallery/IMG_9236.jpg
2008-10-18 @ 03:08:03 RENAMED: gallery/IMG_9228.JPG to gallery/IMG_9228.jpg
2008-10-18 @ 03:08:03 RENAMED: gallery/IMG_3104.JPG to gallery/IMG_3104.jpg
2008-10-18 @ 03:08:03 RENAMED: gallery/First dance02.JPG to gallery/First dance02.jpg
2008-10-18 @ 03:08:03 RENAMED: gallery/BandG02.JPG to gallery/BandG02.jpg
2008-10-18 @ 03:08:03 RENAMED: gallery/official03.JPG to gallery/official03.jpg
2008-10-18 @ 03:08:03 RENAMED: gallery/Wedding32.JPG to gallery/Wedding32.jpg
2008-10-18 @ 03:08:03 RENAMED: gallery/Gettaway car16.JPG to gallery/Gettaway car16.jpg
2008-10-18 @ 03:08:04 CREATED: gallery/thumbs/Afterparty05.jpg
2008-10-18 @ 03:08:04 CREATED: gallery/thumbs/IMG_9254.jpg
2008-10-18 @ 03:08:04 CREATED: gallery/thumbs/IMG_9175.jpg
2008-10-18 @ 03:08:04 CREATED: gallery/thumbs/official05.jpg
2008-10-18 @ 03:08:04 CREATED: gallery/thumbs/First dance01.jpg
2008-10-18 @ 03:08:04 CREATED: gallery/thumbs/Wedding29.jpg
2008-10-18 @ 03:08:04 CREATED: gallery/thumbs/men walking.jpg
推荐答案
$x_amount_of_lines = 30;
$log = 'path/to/log.txt';
if (filesize($log) >= $max_size)) {
$file = file($log);
$line = $file[0];
$file = array_splice($file, 2, $x_amount_of_lines);
$file = array_splice($file, 0, 0, array($line, "\n")); // put the first line back in
...
}
通过rcar进行更正并保存第一行.
edit: with correction from by rcar and saving the first line.
这篇关于如何使用PHP从文本文件的开头删除X行数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文