首页 > 解决方案 > php递归地从所有子文件夹中读取匹配模式的文件

问题描述

我有一个包含多个文件夹的目录。

每个文件夹都有一个文件index.html

index.html 的绝对路径类似于:

C:\Users\Sachin_S2\Desktop\Script\ESXi_6.7_GSG_Pub=9=Validator (XXXX)=en-us\index.html

上面的路径可以解释为:

[Any_folder_location\Script\<Pub_title>=<Pub_version>=Validator (XXXX)=en-us\index.html]

此处的 pub 标题为:ESXi_6.7_GSG_Pub和此处的 Pub 版本为:9

现在,我想使用以下条件(或模式)读取子文件夹中的所有文件:

1)只读 index.html's (跨所有子文件夹)

2)在文件路径中搜索Pub_TitlePub_Version

3)只读那些文件

举个例子。

下面是文件夹结构。

在此处输入图像描述

我当前的脚本:

<?php
$it = new RecursiveDirectoryIterator("C:\Users\Sachin_S2\Desktop\Script");
foreach(new RecursiveIteratorIterator($it) as $file) {
    echo $file . "<br/> \n";

}

脚本输出:

在此处输入图像描述

基本上我想阅读所有搜索 pubtitle 和 pubversion 的 index.htmls。

案例:

带有 ESXi_6.7_GSG_Pub 和版本 9 的 index.html

带有 ESXi_6.7_GSG_Pub 和版本 8 的 index.html

带有 ESXi_6.5_IIG_Pub 和版本 13 等的 index.html

标签: javascriptphp

解决方案


这是我能想到的最好的信息。下次请考虑发布您自己的一些努力以加快速度。2个头总是比一个好。

我在本地模仿了您的文件夹结构,最终得到了这样的结果:

- SomeFolderName 
  - ESXI_6.7GSG_PUB=9=Validator (things)=en-us
     - index.html // contains "index 1"
  - ESXI_6.9GSG_PUB=9=Validator (things)=en-us
     - index.html // contains "index 2"

这显然是虚拟数据结构,我不希望它完全匹配。

考虑到这一点,接下来的事情就是遍历文件夹,您已经在问题中自己完成了。

function recursiveDirectoryIterator($path)
{
    $indexContent = [];

    foreach (new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path)) as $file) {
        if ($file->isDir() && preg_match('/(=[0-9]=)/', $file->getPath())) {
            if (file_exists($file->getPath().'/index.html')) {
                $indexContent[$file->getPath()] = file_get_contents($file->getPath().'/index.html');
            }
        }
    }

    return $indexContent;
}

var_dump(recursiveDirectoryIterator('../SomeFolderName'));

在本地,这给了我

array(2) {
  ["../SomeFolderName/Script/ESXI_6.7GSG_PUB=9=Validator (things)=en-us"]=>
  string(7) "index 1"
  ["../SomeFolderName/Script/ESXI_6.9GSG_PUB=9=Validator (things)=en-us"]=>
  string(7) "index 2"
}

您还会注意到我使用了一个非常简单的 regex /(=[0-9]=)/。它只会查找等号后跟一个数字,然后是一个等号。


我不希望这是一个完整的解决方案,但我确实希望它能让你走上正轨。


推荐阅读