如何删除PHP中的txt文件中的1行?

时间:2016-07-04 07:03:19

标签: php html

如何删除txt文件中的1行?

在TxT中:

1
2
3
4
5
6

我想在Txt文件中删除星期五然后呢?

结果是

1
2
3
4
5

提前谢谢大家!

3 个答案:

答案 0 :(得分:0)

file函数只返回文件的内容(作为数组) - 无论你对该数组做什么,只更改数组,而不是文件。要保留更改,请将内容写回文件:

reference for file function

    $filename = 'test.txt';
    $arr = file($filename);
    if ($arr === false) {
      die('Failed to read ' . $filename);
    }
    array_pop($arr);
    file_put_contents($filename, implode(PHP_EOL, $arr));

答案 1 :(得分:0)

您希望从文件中删除最后一行。
filearray_slicefile_put_contents函数使用以下方法:

$file_name = "weekdays.txt";   // chanhe to your file name 
$lines = file($file_name);    // read the file as an array of lines
$lines = array_slice($lines, 0, -1);  // 'trimming' the last line
file_put_contents($file_name, implode("", $lines));  // writes the remained lines back to file

答案 2 :(得分:0)

对于大文件,您可能希望避免阅读整个内容并将其写回。

您可以改用ftruncate()功能。但是,您首先必须确定最后一行的长度。下面的代码是通过从文件末尾开始定位第一个CR或LF字符来实现的。找到后,它还会检查我们之前是否有另一个CR或LF(因此涵盖了最常见的行尾格式)。

$file = 'myFile.txt';

if(($h = fopen($file, 'r+')) === false) {
  throw new Exception('Failed to open file');
}

$sz = filesize($file);

for($n = -1; $n >= -$sz; $n--) {
  fseek($h, $n, SEEK_END);
  $chr = fgetc($h);

  if($chr == "\n" || $chr == "\r") {
    fseek($h, $n - 1, SEEK_END);
    $chr = fgetc($h);

    if($chr == "\n" || $chr == "\r") {
      $n--;
    }

    ftruncate($h, $sz + $n);
    break;
  }
}
fclose($h);