[英]PHP and regex to find files in directories and then run regex
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.
我将在本地运行php / scripts。
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. 假设我有D:\\ Script \\,我想从中运行我的脚本,还有D:\\ Script \\ folder_01,D:\\ Script \\ folder_02,等等。我希望该脚本从中查找文件。 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". 因此,我不想查找每个文件,而只查找包含以下行的文件:“游戏类型:xxxxx”。 (matching number of text files would be around 150-200)
(文本文件的匹配数量约为150-200)
And after finding those files, I'd like to run some preg_replace one file at a time. 找到这些文件后,我想一次运行一个preg_replace文件。
Thanks. 谢谢。
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: 不过,如果您想为此使用PHP:
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. 如果不需要在其中找到特定字符串的所有文件的列表,则可以将步骤3和4折叠为一个。
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]);
}
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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.