3

I'm trying to skip the first 2 lines (from reading 3 files) then save back (I already got this done, all that's left is the line skipping)

Is there any way to do this?

allenskd
  • 1,795
  • 2
  • 21
  • 33

4 Answers4

6

This is one way of doing it. Perhaps it's a bit overkill, as it's not very efficient. (using file() would be much faster)

$content = file_get_contents($filename);
$lines = explode("\n", $content);
$skipped_content = implode("\n", array_slice($lines, 2));
Dominic Barnes
  • 28,083
  • 8
  • 65
  • 90
3

Yes, but using file_get_contents it would be too complicated. I advise using the file() function instead:

$file_array = file("yourfile.txt");
unset($file_array[0]);
unset($file_array[1]);
file_put_contents("outfile.txt", implode("", $file_array));
Karel Petranek
  • 15,005
  • 4
  • 44
  • 68
  • 3
    file() will load the whole file into memory, just wanted to mention this. I would go with fopen() and reading the file manually in chunks seeking for newline characters or just use strpos($content, "\n") and cut this part of the string. :) – ludesign Feb 15 '11 at 20:07
  • @ludesign: Valid point, thanks. You can post your answer with a sample code :) – Karel Petranek Feb 15 '11 at 20:08
0

use file(), then unset the the first 2 array keys then implode

0

If lines are not very long can't you just use regex on read files? From php manual there is offset parameter in file_get_contents, though this most likely wont be useful since then you need to know line lengths in advance. Maybe file_get_contents isn't proper function to use in this case?

morphles
  • 2,424
  • 1
  • 24
  • 26