Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete first four lines from the top in content stored in a variable

Tags:

php

lines

I have a variable that needs the first four lines stripped out before being displayed:

Error Report Submission
From: First Last, [email protected], 12345
Date: 2009-04-16 04:33:31 pm Eastern

The content to be output starts here and can go on for any number of lines.

I need to remove the 'header' from this data before I display it as part of a 'pending error reports' view.

like image 310
Ian Avatar asked Apr 16 '09 23:04

Ian


2 Answers

Mmm. I am sure someone is going to come up with something nifty/shorter/nicer, but how about:

$str = implode("\n", array_slice(explode("\n", $str), 4));

If that is too unsightly, you can always abstract it away:

function str_chop_lines($str, $lines = 4) {
    return implode("\n", array_slice(explode("\n", $str), $lines));
}

$str = str_chop_lines($str);

EDIT: Thinking about it some more, I wouldn't recommend using the str_chop_lines function unless you plan on doing this in many parts of your application. The original one-liner is clear enough, I think, and anyone stumbling upon str_chop_lines may not realize the default is 4 without going to the function definition.

like image 177
Paolo Bergantino Avatar answered Oct 22 '22 22:10

Paolo Bergantino


$content = preg_replace("/^(.*\n){4}/", "", $content);

like image 4
Bill Fraser Avatar answered Oct 22 '22 23:10

Bill Fraser