.txt 文件删除行但保留前 10 行?

use*_*634 0 php storage if-statement

我将如何删除 .txt 文件中的行?但是保留第一个十行?

到目前为止,这是我的代码:

   <?php 

$hiScore = $_POST['hiScore'] ? $_POST['hiScore'] : 'not set';

$theInput = $_POST['theInput'] ? $_POST['theInput'] : 'not set';

$file = fopen('LeaderBoard.txt','a+');
fwrite($file, ' '.$hiScore.' - Score                                                      Name: '.$theInput.'      '.PHP_EOL);
fclose($file);

$lines = file("LeaderBoard.txt");
natsort($lines);
$lines=array_reverse($lines);
file_put_contents("LeaderBoardScores.txt", implode("\n  \n \n  \n  \n  \n \n  \n", $lines));

$handle = fopen("LeaderBoardScores.txt");
$output = '';
$i = 0;
while (($line = fgets($handle)) !== false) {
    $output .= $line . "\n";
    if ($i++ >= 10)
        break;
}
fclose($handle);
file_put_contents($output, "Leader.txt");

?> 
Run Code Online (Sandbox Code Playgroud)

我不确定如果 staments 在 PHP 中如何工作,但可能会检查文件,如果 lines = 10 以上不向文件发布任何内容?

该人看到的记分板:LeaderBoardScores.txt 应该只看到前 10 名

LeaderBoard.txt 是数据发布的地方,然后被排序供人们在 LeaderBoardScores.txt 中查看

mop*_*922 5

您可以使用循环遍历每一行fgets()并在第 10 行之后跳出:

<?php
$handle = fopen($path_to_file);
$output = '';
$i = 0;
while (($line = fgets($handle)) !== false) {
    $output .= $line . "\n";
    if ($i++ >= 10)
        break;
}
fclose($handle);
file_put_contents($output, $path_to_file);
Run Code Online (Sandbox Code Playgroud)

http://php.net/manual/en/function.fgets.php

In this case, while (($line = fgets($handle)) !== false) loops through the lines in the existing file one-at-a-time. $output collects the content of the lines. $i counts how many lines we've added to $output so far so we can stop (break) at the right time.

  • @ user3112634 您可能应该花*一点*时间来理解这个完全有效的答案。请不要求助于复制/粘贴编程。无论如何,这里没有人会提倡它。 (2认同)