微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

使用 php 递归删除文件 - 仅特定模式 - PHP

如何解决使用 php 递归删除文件 - 仅特定模式 - PHP

搜索了这个网站并尝试了一些建议,但到目前为止没有运气。

我有一堆文件文件名中包含此字符串:“ 2” 例如:test 2.PHP 或 imagename 2.jpg

我想从根文件夹 (/httpsdocs) 和所有子文件夹中删除所有包含“2”字符串的文件

试过这个:

foreach (glob("* 2.*") as $filename) {
    unlink($filename);

这有效,但显然只在根文件夹中。

我怎样才能让它递归地工作?

解决方法

你有没有尝试过这样的事情?

public function removeFilesOnDirectory($path)
{

    $files = glob($path . '/*');
    foreach ($files as $file) {
        if(is_dir($file)) {
            $this->removeDirectory($file);
        } else {
            if (str_contains($file,'2' /* Your constraint */)) {
                unlink($file);
            }
        }
    }

    return;
}

调用这个->removeDirectory(/* 你的路径 */);

对我有用,只是测试一下:)

问候

,

我会使用内置的 RecursiveDirectoryIterator 使其尽可能简单。

<?php

$directoryIterator = new RecursiveDirectoryIterator("/httpsdocs");

foreach(new RecursiveIteratorIterator($directoryIterator) as $file) {
    if(strpos($file->getFilename(),' 2.')) {
        // if filename has specified substring,remove the file
        unlink($file);
    }
}

如果您使用 PHP8,您可以利用新的 str_containt() 函数代替 strpos()。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。