tags:

views:

49

answers:

2

Hi, i have a variable like the following and i want a function to only keep the first 20 lines, so it will strips any additional \n lines more than 20.

<?php
$mytext="Line1
Line2
Line3
....."

keeptwentyline($mytext);
?>
+5  A: 

I suppose a (maybe a bit dumb ^^ ) solution would be to :

  • explode the string into an array of lines
  • keep only the X first lines, using, for instance, array_slice
  • implode those back into a string.


Something like that would correspond to this idea :

var_dump(keepXlines($mytext, 5));

function keepXLines($str, $num=10) {
    $lines = explode("\n", $str);
    $firsts = array_slice($lines, 0, $num);
    return implode("\n", $firsts);
}

Note : I passed the number of lines as a parameter -- that way, the function can be used elsewhere ;-)
And if the parameter is not given, it takes the default value : 10


But there might be some clever way ^^

(that one will probably need qiute some memory, to copy the string into an array, extract the first lines, re-create a string...)

Pascal MARTIN
that's the best I could come up with :)
Andy
I see I'm not the only one who got that idea ^^ *(Even though I would be curious about other ways, actually ^^ )*
Pascal MARTIN
Hmm there is another way I thought of...
Andy
Indeed :-) what I meant was more like *"without explode/implode"* -- ho, I see you've edited your answer, since ;-)
Pascal MARTIN
+6  A: 
function keeptwentyline( $string )
{
     $string = explode( "\n", $string );
     array_splice( $string, 20 );
     return implode( "\n", $string );
}

Or (probably faster)

function keepLines( $string, $lines = 20 )
{
    for( $offset = 0, $x = 0; $x < $lines; $x++ ) {
        $offset = strpos( $string, "\n", $offset ) + 1;
    }

    return substr( $string, 0, $offset );
}
Andy
+1 It should be array_slice, though, not array_splice
soulmerge
http://php.net/manual/en/function.array-splice.php :)
Andy