Reputation: 1488
I want to search for the text Hello
(example) in a TXT file whose size is 5GB+ then return the whole line.
I've tried using SplFileObject
but what I know is that the line number is required to use SplFileObject
, like that:
$linenumber = 2094;
$file = new SplFileObject('myfile.txt');
$file->seek($linenumber-1);
echo $file->current();
But as previously mentioned, I want to search for a string then get the whole line, I don't know the line number.
Any help would be appreciated.
Upvotes: 1
Views: 260
Reputation: 602
this should work:
<?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.
}
Upvotes: 2
Reputation: 1488
This is the answer that I can use. Thanks a lot to @user3783243
For Linux:
exec('grep "Hello" myfile.txt', $return);
For Windows:
exec('findstr "Hello" "myfile.txt"', $return);
Now $return
should contain the whole line.
Unfortunately, this doesn't work if exec()
and system()
functions are disabled by your server administrator in the php.ini file. But for me it works fine.
If someone have a better solution I'd be glad to know it :)
Upvotes: -1