使用php删除前20行以外的所有行

Ahs*_*san 3 php truncate file lines

如何从文本文件中删除除前20行之外的每一行?

cod*_*ict 7

如果将整个文件加载到内存中是可行的,您可以:

// read the file in an array.
$file = file($filename);

// slice first 20 elements.
$file = array_slice($file,0,20);

// write back to file after joining.
file_put_contents($filename,implode("",$file));
Run Code Online (Sandbox Code Playgroud)

一个更好的解决方案是使用函数ftruncate,它接受文件句柄和文件的新大小,如下所示:

// open the file in read-write mode.
$handle = fopen($filename, 'r+');
if(!$handle) {
    // die here.
}

// new length of the file.
$length = 0;

// line count.
$count = 0;

// read line by line.    
while (($buffer = fgets($handle)) !== false) {

        // increment line count.
        ++$count;

        // if count exceeds limit..break.
        if($count > 20) {
                break;
        }

        // add the current line length to final length.
        $length += strlen($buffer);
}

// truncate the file to new file length.
ftruncate($handle, $length);

// close the file.
fclose($handle);
Run Code Online (Sandbox Code Playgroud)


Gor*_*don 5

对于内存有效的解决方案,您可以使用

$file = new SplFileObject('/path/to/file.txt', 'a+');
$file->seek(19); // zero-based, hence 19 is line 20
$file->ftruncate($file->ftell());
Run Code Online (Sandbox Code Playgroud)