Does glob() have negation?

前端 未结 5 1766
执念已碎
执念已碎 2020-12-10 13:47

I know I can do this...

glob(\'/dir/somewhere/*.zip\');

...to get all files ending in .zip, but is there a way to return all f

相关标签:
5条回答
  • 2020-12-10 13:55

    You could always try something like this:

    $all = glob('/dir/somewhere/*.*');
    $zip = glob('/dir/somewhere/*.zip');
    $remaining = array_diff($all, $zip);
    

    Although, using one of the other methods Pascal mentioned might be more efficient.

    0 讨论(0)
  • 2020-12-10 14:03

    I don't think glob can do a "not-wildcard"...

    I see at least two other solutions :

    • use a combinaison of opendir / readdir / closedir
    • Or use some SPL Iterator ; To be more specific, I'm thinking about DirectoryIterator ; and maybe you can combine it with some FilterIterator ?
    0 讨论(0)
  • 2020-12-10 14:04
    $dir = "/path";
    if (is_dir($dir)) {
        if ($d = opendir($dir)) {
               while (($file = readdir($d)) !== false) {
                    if ( substr($file, -3, 3) != "zip" ){
                        echo "filename: $file \n";
                    }
               }
            closedir($d);
        }
    }
    

    NB: "." and ".." not taken care of. Left for OP to complete

    0 讨论(0)
  • 2020-12-10 14:08

    This pattern will work:

    glob('/dir/somewhere/*.{?,??,[!z][!i][!p]*}', GLOB_BRACE);
    

    which finds everything in /dir/somewhere/ ending in a dot followed by either

    • one character (?)
    • or two characters (??)
    • or anything not starting with the consecutive letter z,i,p ([!z][!i][!p]*)
    0 讨论(0)
  • 2020-12-10 14:21

    A quick way would be to glob() for everything and use preg_grep() to filter out the files that you do not want.

    preg_grep('#\.zip$#', glob('/dir/somewhere/*'), PREG_GREP_INVERT)
    

    Also see Glob Patterns for File Matching in PHP

    0 讨论(0)
提交回复
热议问题