【问题标题】:php file_get_contents loop all files in same directoryphp file_get_contents 循环同一目录中的所有文件
【发布时间】:2018-08-24 03:30:39
【问题描述】:

我正在用 PHP 编写一个简单的 cmets 删除脚本。我想做的是为同一目录中的所有文件循环整个脚本。在这一点上,我不关心子目录或子文件夹。此示例只有 1 个文件。我知道我们需要做一个 do..while 循环,但正确的语法是什么?

<?php
$file='home.html';
$page = file_get_contents($file);
$current = preg_replace('<!--[^\[](.*?)-->', '', $page);
file_put_contents($file, $current);
echo $current;
?>

我有一个包含 *.html 文件的文件夹,因此该脚本将读取每个带有 *.html 扩展名的文件并应用 preg_replace。

提前致谢!

V

【问题讨论】:

标签: php while-loop file-get-contents file-put-contents


【解决方案1】:

不久前我写了一个类似你需求的函数:

private function getFilesByPattern($pattern = '*.html', $flags = 0)
{
    $files = glob($pattern, $flags);
    foreach (glob(dirname($pattern) . '/*', GLOB_ONLYDIR | GLOB_NOSORT) as $dir) {
        $files = array_merge($files, $this->getTestFiles($dir . '/' . basename($pattern), $flags));
    }

    return $files;
}

此功能还可以通过子目录进行递归搜索!对于$flags,请查看 glob 的标志:http://php.net/manual/de/function.glob.php

可以这样调用:getTestFiles('../src/directory/*.html')

【讨论】:

    【解决方案2】:
    foreach (glob("*.html") as $file) {
    $page = file_get_contents($file);
    $current = preg_replace('<!--[^\[](.*?)-->', '', $page);
    file_put_contents($file, $current);
    echo $file . "<br>";
    }
    

    这行得通。它从文件夹中的每个 html 文件中删除所有 html cmets。感谢您为我指明正确的方向!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-01-20
      • 2016-11-21
      • 2019-10-12
      • 2022-01-13
      相关资源
      最近更新 更多