在5GB以上的文件中搜索文本,然后整行显示

时间:2019-03-27 14:21:45

标签: php splfileobject

我想在大小为5GB以上的TXT文件中搜索文本Hello(示例),然后返回整行。

我尝试使用SplFileObject,但是我知道使用SplFileObject需要行号,就像这样:

$linenumber = 2094; 
$file = new SplFileObject('myfile.txt');
$file->seek($linenumber-1);
echo $file->current();

但是如前所述,我想搜索一个字符串然后得到整行,我不知道行号。

任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:1)

这应该有效:

<?php
$needle = 'hello';
$count = 1;
$handle = fopen("inputfile.txt", "r");
if ($handle) {
    while (($line = fgets($handle)) !== false) {
        // process the line read.
        $pos = strpos($line, $needle);
        if ($pos !== false) {
            echo $line . PHP_EOL;
            echo "in line: ".$count . PHP_EOL;
            break;
        }
        $count++;
    }

    fclose($handle);
} else {
    // error opening the file.
}

答案 1 :(得分:0)

这是我可以使用的答案。非常感谢@ user3783243

对于Linux:

exec('grep "Hello" myfile.txt', $return);

对于Windows:

exec('findstr "Hello" "myfile.txt"', $return);

现在$return应该包含整行。

不幸的是, 如果服务器管理员在php.ini文件中禁用了exec()system()功能,则此功能不起作用。但是对我来说,它工作正常。

如果有人有更好的解决方案,我很高兴知道:)

相关问题