【问题标题】:Php recursively read files matching a pattern from all subfoldersphp递归地从所有子文件夹中读取匹配模式的文件
【发布时间】:2019-07-18 10:11:08
【问题描述】:

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

每个文件夹都有一个文件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(跨所有子文件夹)

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.html。

案例:

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

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

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

【问题讨论】:

  • explode("\\Script\\", $file) 将为您提供路径 ESXi_6.7_GSG_Pub=9=Validator。从那里,您可以再次使用 explode()_Pub= 来检查 pub 版本。
  • Pub_Title 是否总是具有相同的名称/格式?或者至少是一些常见的模式或ESXi...
  • No Pub_TitlePub_Version 不断变化..
  • 呃,这让事情变得更复杂了。位置总是一样的。就像它总是位于Scripts一样吗?
  • 现在在我的本地,是的,它的Scripts

标签: javascript php


【解决方案1】:

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

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

- 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"
}

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


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

【讨论】:

  • 我只得到像 array(1) { ["C:\Users\Sachin_S2\Desktop\Script\ESXi_6.7_GSG_Pub=9=Validator (Dell)=en-us"]=&gt; string(16071) " "} 这样的单个数组,并且它还在屏幕上显示 html 输出。嗯?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-08-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多