Delete last line in white txt php

Asked

Viewed 1,751 times

1

I have a txt file and need to delete the last line, but it is empty.

I tried the code below and it just erases the top line of the last one that would be blank.

Follows code:

$lines = file('file.txt'); 
$last = sizeof($lines) - 1 ; 
unset($lines[$last]); 


$fp = fopen('file.txt', 'w'); 
fwrite($fp, implode('', $lines)); 
fclose($fp); 
  • Already tried using regular expression ?

  • If you remove the \n of the last element would not solve?

  • I tried this expression $string = preg_replace('/^\s*$/m', '/n', $string);

  • file_put_contents('file.txt',
 implode('', file('file.txt', FILE_SKIP_EMPTY_LINES))); check if it solves.

  • Didn’t work out .

  • and if in place of implode make a while and treat that line ? a little more processing, but I think it solves.

  • have tried rtrim( join('', $lines ) )?

  • No, I’ve never tried, but it’s not really a space it’s an empty blank line.

Show 3 more comments

1 answer

2


This will resolve. Any blank lines will be removed. Remember that a space is not a blank line, just in case, modify the values of the array that are with spaces.

<?php 
$lines = file('file.txt',FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES); 
$fp = fopen('file.txt', 'w'); 
fwrite($fp, implode(PHP_EOL, $lines)); 
fclose($fp); 
  • It worked, that’s right.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.