简体   繁体   中英

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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