我正在寻找在某些文件夹结构中搜索某些字符串的最快方法。我知道我可以使用 file_get_contents 从文件中获取所有内容,但我不确定是否很快。也许已经有一些快速有效的解决方案。我正在考虑使用 scandir 来获取所有文件和 file_get_contents 来读取它的内容和 strpos 来检查字符串是否存在。
你认为有更好的方法吗?
或者也许尝试将 php exec 与 grep 一起使用?
提前致谢!
您的两个选项是DirectoryIterator或glob:
$string = 'something';
$dir = new DirectoryIterator('some_dir');
foreach ($dir as $file) {
$content = file_get_contents($file->getPathname());
if (strpos($content, $string) !== false) {
// Bingo
}
}
$dir = 'some_dir';
foreach (glob("$dir/*") as $file) {
$content = file_get_contents("$dir/$file");
if (strpos($content, $string) !== false) {
// Bingo
}
}
在性能方面,您始终可以计算代码的实时速度或很容易地找出内存使用情况。对于较大的文件,您可能希望使用file_get_contents
.
使用目录迭代器和 foreach: http: //php.net/manual/en/class.directoryiterator.php