簡體   English   中英

如何使用php刪除文件的最后一行?

[英]How can I remove the last line of a file using php?

我嘗試了很多潛在的解決方案,但沒有一個對我有用。 最簡單的一種:

$file = file('list.html');
array_pop($file);

根本沒有做任何事情。 我在這里做錯了嗎? 它是不同的,因為它是一個 html 文件嗎?

這應該有效:

<?php 

// load the data and delete the line from the array 
$lines = file('filename.txt'); 
$last = sizeof($lines) - 1 ; 
unset($lines[$last]); 

// write the new data to the file 
$fp = fopen('filename.txt', 'w'); 
fwrite($fp, implode('', $lines)); 
fclose($fp); 

?>

我創建了一個函數來從底部刪除 x 行。 $max設置$max要刪除的行數。

function trim_lines($path, $max) { 
  // Read the lines into an array
  $lines = file($path);
  // Setup counter for loop
  $counter = 0;
  while($counter < $max) {
    // array_pop removes the last element from an array
    array_pop($lines);
    // Increment the counter
    $counter++;
  }  // End loop
  // Write the trimmed lines to the file
  file_put_contents($path, implode('', $lines));
}

像這樣調用函數:

trim_lines("filename.txt", 1);

變量$path可以是文件的路徑或文件名。

在 PHP 中刪除變量的第一行和最后一行:

使用 phpsh 交互式 shell:

php> $test = "line one\nline two\nline three\nline four";

php> $test = substr($test, (strpos($test, "\n")+1));

php> $test = substr($test, 0, strrpos($test, "\n"));

php> print $test;
line two
line three

您可能的意思是“最后一個非空行”。 在這種情況下,請執行以下操作:

請注意,內容后面有三個空行。 在刪除最后一行之前,這會刪除這些行:

php> $test = "line one\nline two\nline three\nline four\n\n\n";

php> $test = substr($test, 0, strrpos(trim($test), "\n"));

php> print $test;
line one
line two
line three

您只是在讀取文件,現在需要寫入文件

查看file_put_contents

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM