0

我有一个这种形式的大文本文件:

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;

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

4

4 回答 4

1

除非文件太大,否则您可以将其分解

$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 );
于 2013-05-22T11:36:43.257 回答
0

file_get_contents()用和by 双新行读入文件explode,然后用 . 挑出最后一个元素array_pop()

于 2013-05-22T11:35:22.817 回答
0

开始了:

文件.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.

进程.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);
于 2013-05-22T11:36:22.643 回答
0

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

$mystring = file_get_contents('your/file');    
$pos = strrpos($mystring, "\n")
if($pos === false)
    $pos = strrpos($mystring, "\r");
$result = substr($mystring, $pos);
于 2013-05-22T11:55:01.553 回答