简体   繁体   English

删除除特定文件和具有特定扩展名的文件以外的所有文件

[英]Delete All Except Specific Files and Files With Specific Extension

I want to delete all files in a folder except files containing: 我要删除文件夹中的所有文件,但包含以下内容的文件除外:

  1. Specific file names 特定文件名
  2. Specific file extensions 特定的文件扩展名

The following code succeeds in the above first point, but not the second point. 以下代码在上述第一点成功,但在第二点不成功。

   function deletefiles()
    {
    $path = 'files/';

    $filesToKeep = array(
        $path."example.jpg",
        $path."123.png",
        $path."*.mkv"
    );

    $dirList = glob($path.'*');

    foreach ($dirList as $file) {
        if (! in_array($file, $filesToKeep)) {
            if (is_dir($file)) {
                rmdir($file);
            } else {
                unlink($file);
            }//END IF
        }//END IF
    }//END FOREACH LOOP
    }

How can I achieve both conditions? 我怎样才能同时达到这两个条件?

You need to change a bit your function: 您需要更改一下功能:

    <?php

function deletefiles()
{
    $path = 'files/';

    $filesToKeep = array(
        $path . "example.jpg",
        $path . "123.png",

    );

    $extensionsToKeep = array(
        "mkv"
    );

    $dirList = glob($path . '*');

    foreach ($dirList as $file) {

        if (!in_array($file, $filesToKeep)) {
            if (is_dir($file)) {
                rmdir($file);
            } else {
                $fileExtArr = explode('.', $file);
                $fileExt = $fileExtArr[count($fileExtArr)-1];
                if(!in_array($fileExt, $extensionsToKeep)){
                    unlink($file);
                }
            }//END IF
        }//END IF
    }
}

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

相关问题 如何删除目录中除PHP中特定文件夹外的所有文件夹和文件 - How to delete all folders and files in a directory except a specific folder in PHP 仅为特定文件而不是特定扩展名的所有文件启用 PHP - Enable PHP for only a specific file instead of all files of a specific extension 在特定时间后从目录和所有子目录中修改的PHP删除(.extension)文件 - PHP delete (.extension) files that are modified after specific time from directory and all sub-directories 删除除具有特定类的div以外的所有div吗? - Delete all divs except a div with a specific class? 如何扫描目录和所有子目录中的特定文件(扩展名为.php) - How to scan a directory and all subdirectorys for specific files (with .php extension) PHP删除除以下内容之外的所有文件 - PHP Delete all files except the following PHP,删除特定目录中具有特定扩展名的文件,只要超过(10)分钟 - PHP, delete files in a specific directory with a specific extension as long as it's over (10) minutes old Cron作业 - 删除特定文件夹中的所有文件 - Cron Job - delete all files inside a specific folder 如何在特定时间后删除文件夹中的所有文件 - How to delete all files in folder after specific time 删除所有名称以特定字符串结尾的文件 - Delete all files that it's name end with specific string
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM