Scanning files for a specific string

June 11, 2008 – 7:21 pm

Over 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:

  1. < ?php
  2. // list file extensions that you care about here
  3. $extensions = array('php','inc');
  4.  
  5. foreach(new RecursiveIteratorIterator(new RecursiveDirectoryIterator('.')) as $Item)
  6. {
  7.     if ($Item->isFile() and in_array(pathinfo($Item->getFilename(),PATHINFO_EXTENSION),$extensions))
  8.     {
  9.         foreach($Item->openFile() as $linenum => $line)
  10.         {
  11.             // add the code to check your pattern here
  12.             if (stripos($line,'class') !== false) {
  13.                 echo $Item->getPathname(), ':', $linenum, ' ', $line;
  14.             }
  15.         }
  16.     }
  17. }

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.

Post a Comment