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

后端 未结 4 2023
悲哀的现实
悲哀的现实 2021-01-12 02:37

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);
相关标签:
4条回答
  • 2021-01-12 03:09

    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.

    0 讨论(0)
  • 2021-01-12 03:17

    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
    
    0 讨论(0)
  • 2021-01-12 03:25

    This should works :

    <?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); 
    
    ?>
    
    0 讨论(0)
  • 2021-01-12 03:30

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

    Look into file_put_contents etc

    0 讨论(0)
提交回复
热议问题