假设我有一个大文件。该文件是一个IP列表,每个IP都在新的一行上,就像这样:
123.123.123.123
123.123.123.124
123.123.123.125
etc...
我可以这样做:
$file = file_get_contents($src);
if (substr_count($file,'myip'))
echo 'FOUND';
或者使用类似数组的方式:
$file = file($src,FILE_IGNORE_NEW_LINES);
if (in_array('myip',$file))
echo 'FOUND';
但我认为有第三种选择可能更快。
逐行解析文件,并在找到字符串后停止读取。
就像这样:
$file = fopen($src,'r');
while(!feof($file)) {
$ip = fgets($file);
if ($ip == $myIP) {
die('Found');
}
}
fclose($file);
我的问题是:你认为还有其他更好的方法吗?
就性能而言,你认为哪个代码更快?
非常感谢大家。
grep
或find
这样的命令行工具吗? - Pekkagrep $myIP $file
)die('found'); - symcbean