tags:

views:

561

answers:

4

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.

+7  A: 

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.

Paolo Bergantino
thanks for the help :)
Ian
I believe your first example is easier to glance over and understand it's meaning quicker than other 1 line solutions. 'plus uno' :P
alex
Yeah, at first I thought it was ugly but it's pretty clear on what it does, I think.
Paolo Bergantino
add the extra "limit" parameter to the explode function for more efficiency: explode("\n", $str, 5)
nickf
+1  A: 

Split the string into an array using split(rex), where rex matches two consecutive newlines, and then concatenate the entire array, except for the first element (which is the header).

Deniz Dogan
+2  A: 

Strpos helps out a lot: Here's an example:

// $myString = "blah blah \n \n \n etc \n \n blah blah";

$len = strpos($myString, "\n\n"); 
$string = substr($myString, $len, strlen($myString) - $len);

$string then contains the string after finding those two newlines in a row.

Tony k
Have you tested this? It it not working me, strpos returns the position of the first occurrence, not whatever comes after.
Paolo Bergantino
Sorry about that - edited my post to do it a different way and left out the part that actually did it!
Tony k
Have you tested _this_? :) It's not working either. I'm not sure why, though.
Paolo Bergantino
Yeah - http://www.kanago.net/loltest.php and the same .phps has it. The commented out string actually has spaces between newlines unlike the actual string. Oopsies. Embarrass me enough yet? :D
Tony k
Haha, just looking out. :) I wasn't testing it with the string you gave, though, it isn't working on my machine with the string the OP gave. Odd. *Shrug*
Paolo Bergantino
+2  A: 

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

Graycode