【问题标题】:How to delete all files in all sub-folders except those whose filename is 'whatever.jpg' in PHP?如何删除所有子文件夹中的所有文件,除了那些在 PHP 中文件名为“whatever.jpg”的文件?
【发布时间】:2012-07-17 20:09:29
【问题描述】:

删除所有子文件夹除了文件名为'的所有文件的最快方法是什么PHP中的whatever.jpg'?

【问题讨论】:

标签: php file directory filesystems delete-file


【解决方案1】:

为什么不使用迭代器?这是经过测试的:

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');

【讨论】:

  • 非常有趣,谢谢。使用“@unlink”和只使用“unlink”有什么区别?
【解决方案2】:

这应该是你要找的,$but 是一个包含异常的数组。 不确定它是否最快,但它是最常用的目录迭代方式。

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

使用示例:

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

【讨论】:

    【解决方案3】:

    未经测试:

    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('.');
    

    【讨论】:

    • 注意scandir()是在PHP5中添加的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多