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

时间:2022-04-23 11:13:13

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.

我正在寻找最快的方法来搜索某些文件夹结构中的字符串。我知道我可以使用file_get_contents从文件中获取所有内容,但我不确定是否快速。也许已经有一些解决方案可以快速运行。我正在考虑使用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!

提前致谢!

2 个解决方案

#1


13  

Your two options are DirectoryIterator or glob:

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

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的替代方法。

#2


2  

use directory iterator and foreach: http://php.net/manual/en/class.directoryiterator.php

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

#1


13  

Your two options are DirectoryIterator or glob:

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

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的替代方法。

#2


2  

use directory iterator and foreach: http://php.net/manual/en/class.directoryiterator.php

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