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!
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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With