jemtan990
jemtan990

Reputation: 453

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

I've tried a lot of potential solutions, but none of them are working for me. The simplest one:

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

isn't doing anything at all. Am I doing something wrong here? Is it different because it's an html file?

Upvotes: 13

Views: 22512

Answers (5)

Xavier
Xavier

Reputation: 4017

This should work :

<?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 
file_put_contents('filename.txt', $lines); 

Upvotes: 20

wp-mario.ru
wp-mario.ru

Reputation: 914

In a simple case, I use the following code:

$text = file_get_contents( 'FILE_PATH' );
$pos = strrpos( $text, PHP_EOL );
$text = substr( $text, 0, $pos );
file_put_contents( 'FILE_PATH', $text );

Or a slightly extended version to check if the file ends with a line break:

$text = file_get_contents( 'FILE_PATH' );
$offset = mb_substr( $text, -1 ) == PHP_EOL ? -2 : 0;
$pos = strrpos( $text, PHP_EOL, $offset );
$text = $offset === 0 ? substr( $text, 0, $pos ) : substr( $text, 0, $pos ) . PHP_EOL;
file_put_contents( 'FILE_PATH', $text );

Upvotes: 1

pmagunia
pmagunia

Reputation: 1788

I created a function to remove x number of lines from the bottom. Set $max to the number of lines you want to delete.

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));
}

Call the function like this:

trim_lines("filename.txt", 1);

The variable $path can be a path to the file or a filename.

Upvotes: 1

Kris
Kris

Reputation: 6112

You are only reading the file, you now need to write the file

Look into file_put_contents etc

Upvotes: -3

Eric Leschinski
Eric Leschinski

Reputation: 153852

Remove first and last line of a variable in PHP:

Using phpsh interactive 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

You might have meant "The last non blank line". In that case do this:

Notice that there are three blank lines after the content. This gets rid of those lines before removing the last:

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

Upvotes: 0

Related Questions