【问题标题】:Searching all files in folder for strings在文件夹中的所有文件中搜索字符串
【发布时间】:2013-02-09 02:23:29
【问题描述】:

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

您认为有更好的方法吗?

或者也许尝试将 php exec 与 grep 一起使用?

提前致谢!

【问题讨论】:

标签: php linux


【解决方案1】:

您的两个选项是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
    }
}

在性能方面,您总是可以很容易地compute the real-time speed of your code 或找出memory usage。对于较大的文件,您可能需要使用 an alternativefile_get_contents

【讨论】:

  • 您的解决方案检查文件名,我需要检查文件内容。代码有很大区别吗?
【解决方案2】:

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

【讨论】:

  • 比 grep 和 file_get_contents 快吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-06-11
  • 2021-12-15
  • 2011-12-12
  • 2018-11-27
相关资源
最近更新 更多