The fastest way to find out if a string is found in a file?

Say I have a large file. The file is a list of IP addresses in each new line:

123.123.123.123
123.123.123.124
123.123.123.125
etc...

I could do it like this:

$file = file_get_contents($src);    
if (substr_count($file,'myip'))
    echo 'FOUND';

Or a similar way with array style:

$file = file($src,FILE_IGNORE_NEW_LINES);
if (in_array('myip',$file))
    echo 'FOUND';

But I think there is a third option, which can be faster.
Parsing a line by line and, of course, stopping reading if a line is found.

Something like that:

$file = fopen($src,'r');
while(!feof($file)) { 
    $ip = fgets($file);
    if ($ip == $myIP) {
        die('Found');
    }   
}
fclose($file);

My question is: do you think there is another better way?

And in terms of performance, which code do you think is faster?

Thank you very much guys

+3
source share
3 answers

, grep find. , , , PHP.

+1

, , , , , , .

$file = fopen($src,'r');
while(!feof($file)) { 
    $ip = fgets($file);
    if ($ip == $myIP) {
        echo 'FOUND!';
        break; // dieing here won't close the file
    }   
}

fclose($file);
0

If you can save the file sort, then performing a binary search will do well.

However, sorting the file will take some time, so if you do a lot of attachments / deletions, this may not be very efficient.

0
source

All Articles