从文本文件输出最后一个文本块(以空行分隔)


output last block of text(separated by empty lines) from a text file

我有一个大的文本文件:

This is a linie of text.
This is a linie of text.
This is a linie of text.
This is a linie of text.
This is a linie of text.
This is a linie of text.
This is a linie of text.
This is a linie of text.
This is a linie of text.

等。我想输出最后几个块/文本块从这个文件在我的网站。我现在使用这个:

$line = '';
$f = fopen('output.log', 'r');
$cursor = -1;
fseek($f, $cursor, SEEK_END);
$char = fgetc($f);
/**
 * Trim trailing newline chars of the file
 */
while ($char === "'n" || $char === "'r") {
    fseek($f, $cursor--, SEEK_END);
    $char = fgetc($f);
}
/**
 * Read until the start of file or first newline char
 */
while ($char !== false && $char !== "'n" && $char !== "'r") {
    /**
     * Prepend the new char
     */
    $line = $char . $line;
    fseek($f, $cursor--, SEEK_END);
    $char = fgetc($f);
}
echo $line;

只显示最后一行。任何关于这个的想法都会很棒!谢谢!编辑:所有的块用空行分隔,脚本应该打印最后几个块

除非文件太大,否则可以将其展开

$allLines = explode("'n", file_get_contents('your/file') );
$endLines = array_slice( $allLines, -2 );
echo implode("'n", $endLines );

如果要匹配包含任意行数的块,可以使用双换行符"'n'n"

如果空白字符不可靠地一致,则可以使用preg_match。例如

$allBlocks = preg_split( '/['n'r]'s*['n'r]/', file_get_contents('your/file'), -1, PREG_SPLIT_NO_EMPTY );

开始:

file.txt

This is a linie of text.
This is a linie of text.
This is a linie of text.
This is a linie of text.
This is a linie of text.
This is a linie of text.
This is a linie of text.
This is a linie of text.
This is a linie of text.

process.php:

$fileContents = file('file.txt', FILE_SKIP_EMPTY_LINES);
$numberOfLines = count($fileContents);
for($i = $numberOfLines-2; $i<$numberOfLines; $i++)
{
    echo $fileContents[$i];
}

这将输出文件

中的最后两行文本。

或者,使用substr返回文本的最后50个字母:

$fileContents = file_get_contents('file.txt');
echo subtr($fileContents, -50, 50);

以双换行方式读入file_get_contents()explode的文件,然后挑出array_pop()的最后一个元素

对于大文件,此代码将比正则表达式运行得更快。

$mystring = file_get_contents('your/file');    
$pos = strrpos($mystring, "'n")
if($pos === false)
    $pos = strrpos($mystring, "'r");
$result = substr($mystring, $pos);