简体   繁体   English

搜索文件夹中的所有文件以查找字符串

[英]Searching all files in folder for strings

I am looking for the fastest approach for searching for some string into some folder structure. 我正在寻找最快的方法来搜索某些文件夹结构中的字符串。 I know that I can get all content from the file with file_get_contents, but I am not sure if is fast. 我知道我可以使用file_get_contents从文件中获取所有内容,但我不确定是否快速。 Maybe there is already some solution that works fast. 也许已经有一些解决方案可以快速运行。 I was thinking about using scandir to get all files and file_get_contents to read it's content and strpos to check if the string exist. 我正在考虑使用scandir获取所有文件和file_get_contents来读取它的内容并使用strpos来检查字符串是否存在。

Do you think there is some better way od doing this? 你认为有更好的方法吗?

Or maybe trying to use php exec with grep? 或者也许尝试使用php exec和grep?

Thanks in advance! 提前致谢!

Your two options are DirectoryIterator or glob : 您的两个选项是DirectoryIteratorglob

$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
    }
}

In terms of performance, you can always compute the real-time speed of your code or find out memory usage quite easily. 在性能方面,您始终可以非常轻松地计算代码的实时速度或查找内存使用情况 For larger files, you might want to use an alternative to file_get_contents . 对于较大的文件,您可能希望使用file_get_contents 的替代方法

使用目录迭代器和foreach: http//php.net/manual/en/class.directoryiterator.php

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM