php file_get_contents循环同一目录中的所有文件 [英] php file_get_contents loop all files in same directory

查看:80
本文介绍了php file_get_contents循环同一目录中的所有文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm working on a simple comments removal script in PHP. What I'd like to do is loop this entire script for all the files in the same directory. At this point I'm not concerned with subdirectories or subfolder. This example only has 1 file. I know we need to do a do..while loop but what would be the proper syntax?

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

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

I have a folder filled with *.html files so this script would read each file with the *.html extension and apply the preg_replace.

提前谢谢!

V

推荐答案

不久前,我编写了一个与您的需求类似的函数:

I wrote a function similar to your needs not long ago:

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

This function also searches recusively through sub directories! For $flags look into the flags of glob: http://php.net/manual/de/function.glob.php

可以这样称呼: getTestFiles('../src/directory/*.html')

这篇关于php file_get_contents循环同一目录中的所有文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆