Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: How to seek backwards to find last N lines

Tags:

php

tail

I suppose I could call tail, but that would mean depending on an external program. Is there a way to do this in an efficient way using only PHP?


Update: For those interested, I followed the advice I got in the accepted answer and tried to implement on myself. Put it on my blog =)

like image 739
Svish Avatar asked May 26 '11 19:05

Svish


Video Answer


1 Answers

So you want the last n lines of a string?

function getLastLines($string, $n = 1) {
    $lines = explode("\n", $string);

    $lines = array_slice($lines, -$n);

    return implode("\n", $lines);
}

You can then call this with getLastLines($str, $num);, where $num is a positive integer and $str is a string you want to chop up.

If you want something different, e.g. using a file as the source, you'll need something different -- perhaps using file instead of explode.

like image 182
lonesomeday Avatar answered Sep 23 '22 18:09

lonesomeday