/ / fwriteの実行中に.txtファイルから最後の段落をトリミングする-php

fwrite-phpの実行中に.txtファイルから最後の段落を削除する

私は以下のPHPコードを使用して自分に書き込みます wall.txt ファイル。それはうまくいきますが、問題はそれです wall.txt ファイルサイズは増え続けています。トリミングしたい wall.txt 3段落後に新しいデータが追加されるとファイル。古い段落は削除され、新しい段落が追加されます。

これが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:04pm **** 男の子: 911に電話します こんにちは?あなたの助けが必要です!/-%/ 911:わかりました、それはなんですか?/-%/男の子:2人の女の子が私をめぐって争っています!/-%/ 911:それであなたは何ですか 緊急?/-%/男の子:醜い人が勝っています。|金曜日、05:36:19pm ****今年のダイエットに最も近いのは、ブラウザの履歴から食べ物の検索を消去することです。/-%//-%/ Lollzzzzz:p |金曜日、 05:44:35 pm


回答:

回答№1は0

使用するソリューション file そして array_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));