Scanning files for a specific string
June 11, 2008 – 7:21 pmOver at DevNetwork forums somebody asked for a piece of code, that scans a directory containing thousands of files for a file containg specific string.
Here is the solution I came up with it:
-
< ?php
-
// list file extensions that you care about here
-
$extensions = array('php','inc');
-
-
foreach(new RecursiveIteratorIterator(new RecursiveDirectoryIterator('.')) as $Item)
-
{
-
if ($Item->isFile() and in_array(pathinfo($Item->getFilename(),PATHINFO_EXTENSION),$extensions))
-
{
-
foreach($Item->openFile() as $linenum => $line)
-
{
-
// add the code to check your pattern here
-
if (stripos($line,'class') !== false) {
-
echo $Item->getPathname(), ':', $linenum, ' ', $line;
-
}
-
}
-
}
-
}
Upside: it scans the directory structure recursively and the code is quite clean, besides maybe the pathinfo call to filter out filenames with specific extension.
Downside: it’s slow. In real life grep or some other tool is used for task like this.
Still, the code shows the power of SPL File- & DirectoryIterators nicely.
