search文件夹中的所有文件的string

我正在寻找最快的方法来search一些string到一些文件夹结构。 我知道我可以用file_get_contents从文件中获取所有内容,但是我不确定是否快。 也许已经有一些快速的解决scheme。 我正在考虑使用scandir来让所有文件和file_get_contents读取它的内容和strpos来检查string是否存在。

你认为有更好的方法吗?

或者也许试图使用PHP的执行与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