CodeOverload
CodeOverload

Reputation: 48545

PHP how to limit lines in a string?

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

Upvotes: 4

Views: 5354

Answers (2)

Andy
Andy

Reputation: 17791

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

Upvotes: 8

Pascal MARTIN
Pascal MARTIN

Reputation: 401182

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

Upvotes: 11

Related Questions