Reputation: 3
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.
Upvotes: 0
Views: 2792
Reputation: 3
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);
}
Upvotes: 0
Reputation: 9397
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:
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]);
}
Upvotes: 1