www.webdeveloper.com
Results 1 to 2 of 2

Thread: Remove last line in a file PHP/Store all lines except the last one

  1. #1
    Join Date
    Mar 2008
    Posts
    32

    Remove last line in a file PHP/Store all lines except the last one

    Hello all! Is there a way to remove the last line in a text file? Or, alternatively, is there a way to read a text file until the penultimate line of the file?
    That is, if you have a file like:
    Code:
    AAAA
    BBBB
    CCCC
    DDDD
    XXXXXXXX
    read all lines except the last one? In the previous example I need to hold only AAAA, BBBB , CCCC and DDDD.
    Thank you!

  2. #2
    Join Date
    Aug 2004
    Location
    Ankh-Morpork
    Posts
    19,633
    One way:
    PHP Code:
    $lines file('path/to/file'FILE_IGNORE_NEW_LINES FILE_SKIP_EMPTY_LINES);
    array_pop($lines); // remove last line 
    At this point $lines would be an array where each element is one line from the file, sans the last line. You could do a foreach() on it to loop through each line, or write it back to the file:
    PHP Code:
    file_put_contents('path/to/file'implode("\n"$lines)); 
    "Please give us a simple answer, so that we don't have to think, because if we think, we might find answers that don't fit the way we want the world to be."
    ~ Terry Pratchett in Nation

    eBookworm.us

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles