Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Searching all files in folder for strings

Tags:

linux

php

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!

like image 636
Bob Avatar asked Feb 23 '13 14:02

Bob


People also ask

How do you search all the files in a directory for a string?

You need to use the grep command. The grep command or egrep command searches the given input FILEs for lines containing a match or a text string.


1 Answers

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.

like image 152
hohner Avatar answered Oct 19 '22 10:10

hohner