在进行fwrite时,从.txt文件中修剪最后一段


trimming last paragraph from .txt file while doing fwrite

我正在使用下面的PHP代码来写入我的wall.txt文件。它运行良好,但问题是wall.txt文件大小不断增加。我想在3段之后添加新数据后修剪wall.txt文件。旧段落将被删除,而新段落将被添加

这是php文件

  <?php
    $joke = $_POST['AndroidString'];

     $complexString = ($joke . "|" . date("l") . ", " . date("jS 'of F Y h:i:s A"));
   $endLineStericks = "****";

        $registrationFile = fopen("wall.txt", "a") or die("Unable to open file!");
   fwrite($registrationFile, $complexString);
  fwrite($registrationFile, "'n");
 fwrite($registrationFile, $endLineStericks);
 fwrite($registrationFile, "'n");
 fclose($registrationFile);

   ?>

这是文本文件

男孩:校长太笨了!/-%/女孩:你知道我是谁吗?/-%/男孩:不…/-%/女孩:我是校长的女儿!/-%/男孩:你知道是谁吗我是?/-%/女孩:不……/-%/男孩:好走开|星期五下午05:23:04****男孩:打911喂?我需要你的帮助!/-%/911:好吧,是什么?/-%/男孩:两个女孩在为我打架!/-%/911:那么你的紧急情况?/-%/男孩:丑陋的那个赢了|星期五,下午05:36:19****最接近我™我今年节食了,从我的浏览器历史记录中删除了食物搜索。/-%//-%/Lollzzzzz:p|星期五,下午05:44:35


使用filearray_slice函数的解决方案:

define("WALL", "wall.txt");
$joke = $_POST['AndroidString'];
fopen(WALL, 'a') || die("Failed to open file!");
$contents = file(WALL); // gets file contents as array of strings(lines)
$complexString = ($joke . "|" . date("l") . ", " . date("jS 'of F Y h:i:s A")). PHP_EOL;
$endLineStericks = "****" . PHP_EOL;
$contents = array_merge($contents, [$complexString, $endLineStericks]);
 // if there were at least three records(including end stricks) in wall.txt
if (count($contents) > 6) {
    $contents = array_slice($contents, -6); // getting last three records
}
file_put_contents(WALL, implode("", $contents));