在文件夹中的所有文件中搜索字符串 [英] Searching all files in folder for strings

查看:408
本文介绍了在文件夹中的所有文件中搜索字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找将某些字符串搜索到某些文件夹结构中的最快方法.我知道我可以使用file_get_contents从文件中获取所有内容,但是我不确定是否很快.也许已经有一些可以快速运行的解决方案.我当时正在考虑使用scandir获取所有文件,并使用file_get_contents读取其内容,并使用strpos来检查字符串是否存在.

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. 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.

您认为这样做有更好的方法吗?

Do you think there is some better way od doing this?

还是尝试在grep中使用php exec?

Or maybe trying to use php exec with grep?

提前谢谢!

推荐答案

您的两个选项是 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的替代方法.

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.

这篇关于在文件夹中的所有文件中搜索字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆