简体   繁体   English

如何删除所有子文件夹中的所有文件,除了那些文件名为'whatever.jpg'的PHP文件?

[英]How to delete all files in all sub-folders except those whose filename is 'whatever.jpg' in PHP?

什么是删除除了那些文件名是“whatever.jpg”在PHP中所有子文件夹中的所有文件最快的方法?

Why not use iterators? 为什么不使用迭代器? This is tested: 经测试:

function run($baseDir, $notThis)
{
    foreach (new RecursiveIteratorIterator(new RecursiveDirectoryIterator($baseDir), RecursiveIteratorIterator::LEAVES_ONLY) as $file) {
        if ($file->isFile() && $file->getFilename() != $notThis) {
            @unlink($file->getPathname());
        }
    }
}

run('/my/path/base', 'do_not_cancel_this_file.jpg');

This should be what youre looking for, $but is an array holding exceptions. 这应该是你要找的, $but是一个包含异常的数组。 Not sure if its the fastest , but its the most common way for directory iteration. 不确定它是否是最快的 ,但它是目录迭代最常用的方式。

function rm_rf_but ($what, $but)
{
    if (!is_dir($what) && !in_array($what,$but))
        @unlink($what);
    else
    {
        if ($dh = opendir($what))
        {
            while(($item = readdir($dh)) !== false)
            {
                if (in_array($item, array_merge(array('.', '..'),$but)))
                    continue;
                rm_rf_but($what.'/'.$item, $but);
            }
        }

        @rmdir($what); // remove this if you dont want to delete the directory
    }
}

Example use: 使用示例:

rm_rf_but('.', array('notme.jpg','imstayin.png'));

Untested: 未经测试:

function run($baseDir) {
    $files = scandir("{$baseDir}/");
    foreach($files as $file) {
        $path = "{$badeDir}/{$file}";
        if($file != '.' && $file != '..') {
            if(is_dir($path)) {
                run($path);
            } elseif(is_file($path)) {
                if(/* here goes you filtermagic */) {
                    unlink($path);
                }
            }
        }
    }
}
run('.');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM