[英]Search for text in a 5GB+ file then get whole line
我想在大小為 5GB+ 的 TXT 文件中搜索文本Hello
(示例),然后返回整行。
我試過使用SplFileObject
但我知道使用SplFileObject
需要行號,如下所示:
$linenumber = 2094;
$file = new SplFileObject('myfile.txt');
$file->seek($linenumber-1);
echo $file->current();
但如前所述,我想搜索一個字符串然后獲取整行,我不知道行號。
任何幫助,將不勝感激。
這應該有效:
<?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.
}
這是我可以使用的答案。 非常感謝@user3783243
對於 Linux:
exec('grep "Hello" myfile.txt', $return);
對於 Windows:
exec('findstr "Hello" "myfile.txt"', $return);
現在$return
應該包含整行。
不幸的是,如果您的服務器管理員在 php.ini 文件中禁用了exec()
和system()
函數,這將不起作用。 但對我來說它工作正常。
如果有人有更好的解決方案,我很高興知道:)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.