Php 在5GB+;文件,然后得到整行
我想在一个大小为5GB+的TXT文件中搜索文本Php 在5GB+;文件,然后得到整行,php,splfileobject,Php,Splfileobject,我想在一个大小为5GB+的TXT文件中搜索文本Hello(示例),然后返回整行 我尝试过使用SplFileObject,但我知道使用SplFileObject需要行号,如下所示: $linenumber = 2094; $file = new SplFileObject('myfile.txt'); $file->seek($linenumber-1); echo $file->current(); 但正如前面提到的,我想搜索一个字符串,然后得到整行,我不知道行号 任何帮助都将不
Hello
(示例),然后返回整行
我尝试过使用SplFileObject
,但我知道使用SplFileObject
需要行号,如下所示:
$linenumber = 2094;
$file = new SplFileObject('myfile.txt');
$file->seek($linenumber-1);
echo $file->current();
但正如前面提到的,我想搜索一个字符串,然后得到整行,我不知道行号
任何帮助都将不胜感激。这是我可以使用的答案。非常感谢@user3783243 对于Linux:
exec('grep "Hello" myfile.txt', $return);
exec('findstr "Hello" "myfile.txt"', $return);
适用于Windows:
exec('grep "Hello" myfile.txt', $return);
exec('findstr "Hello" "myfile.txt"', $return);
现在,$return
应该包含整行
不幸的是,如果服务器管理员在php.ini文件中禁用了exec()
和system()
函数,则此功能不起作用。但对我来说效果很好
如果有人有更好的解决方案,我很高兴知道:)这应该可以:
<?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.
}
你试过用一个简单的计数器吗?你可以用循环一行一行地读取文件吗?我认为并行化进程可能很有用,例如,一个进程从上到下读取,同时另一个进程从下到上读取。行的大小是多少?您只需要第一次出现,还是需要包含搜索字符串的所有行?@programmer man-这行大约有100个字符,而且我要查找的字符串只有一次出现。@Robii解决方案似乎是最好的方法。您可以执行类似于exec的操作('grep“Hello”myfile.txt',$return)代码>不应该有一个中断代码>行在中,而循环一旦找到该行?