4

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);
?>

2 Answers 2

11

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...)

Sign up to request clarification or add additional context in comments.

3 Comments

that's the best I could come up with :)
I see I'm not the only one who got that idea ^^ (Even though I would be curious about other ways, actually ^^ )
Indeed :-) what I meant was more like "without explode/implode" -- ho, I see you've edited your answer, since ;-)
8
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);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.