alex
alex

Reputation: 490303

Does glob() have negation?

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 files that are not ZIPs?

Or should I just iterate through and filter off ones with that extension?

Upvotes: 14

Views: 10356

Answers (5)

Pascal MARTIN
Pascal MARTIN

Reputation: 401032

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

I see at least two other solutions :

Upvotes: 9

Gordon
Gordon

Reputation: 316999

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]*)

Upvotes: 9

salathe
salathe

Reputation: 51950

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

Upvotes: 18

ghostdog74
ghostdog74

Reputation: 342443

$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

Upvotes: 0

Atli
Atli

Reputation: 7930

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.

Upvotes: 28

Related Questions