views:

267

answers:

2

hi, what's the the most efficient way to find text files in different directories and then run regex to those found files. I will run php/scripts locally.

Let's say I have D:\Script\ where i want to run my script from and D:\Script\folder_01, D:\Script\folder_02, etc. where i want that script to look the files from. Those folder names aren't logical, they could be anything.

So, i don't want to find every files but only the files that contains the line: "Game type: xxxxx". (matching number of text files would be around 150-200)

And after finding those files, I'd like to run some preg_replace one file at a time.

Thanks.

+1  A: 

If you're going to run this locally, other languages are probably faster and or easier to implement.

Nevertheless, if you want to use PHP for this:

  1. Recursively make a list of all the files from a certain directory downwards. So that could be D:\scripts\foo and D:\scripts\foo\bar etc... (use a recursive function, scandir() etc).
  2. Per file save the complete path in which you found the file and the file name.
  3. Now walk through the array and for every file you find call a function that opens that file, does a regex on every line for the desired string and return TRUE if that string is found. If the function returns TRUE, save the path+filename in a second array. You now have a list of all the files that contain the desired string.
  4. Walk through the second array you made, per file call a function that opens the file, reads every line and does a preg_replace().

Steps 3 and 4 can be folded into one if you don't need a list of all the files where you find a certain string.

In code:

$fileList = giveFileList('D:\scripts\foo');
$selectedFileList = array();
for( $i = 0 ; $i < count($fileList) ; $i++ )
{
    if(stringExistsInFile($fileList[$i]))
    {
        $selectedFileList[] = $fileList[$i];    
    }
}

for( $i = 0 ; $i < count($selectedFileList) ; $i++ )
{
    replaceStringInFile($selectedFileList[$i]);
}
Niels Bom
A: 

Will this do the whole trick? Or am I missing something crucial? Sorry i'm a newbie! :)

if ($handle = opendir('/scripts')) {
    while (false !== ($filename = readdir($handle))) {
       $openFile = fopen($filename, "r")  or die("Can't open file");
       $file = fread($openFile, filesize($filename));
       $pattern = '/^Game Type: xxx$/im';
       if (preg_match($pattern, $file)) {
         // preg_replace goes here
         // fopen newFile goes here
         // fwrite newFile goes here
         // fclose newFile goes here
       }
       fclose($openFile);
    }

    closedir($handle);
}
mika