Reputation: 48545
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
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
Reputation: 401182
I suppose a (maybe a bit dumb ^^ ) solution would be to :
explode
the string into an array of linesarray_slice
implode
those back into a string.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
(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