Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

Or maybe trying to use php exec with grep?

Thanks in advance!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
392 views
Welcome To Ask or Share your Answers For Others

1 Answer

Your two options are DirectoryIterator or 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...