user702300
user702300

Reputation: 1241

PHP glob() to list file that doesn't start with underscore?

The standard glob() function usage is like

$dir = glob("*.txt");
foreach ($dir as $filename) {
    echo "$filename size " . filesize($filename) . "\n";
}

using * as wildcard, but is there a way to negate it to ignore any file that starts with underscore like _something.txt? I am trying to avoid using preg_match() like

$dir = glob("*.txt");
foreach ($dir as $filename) {
    if (! preg_match("^_+", $filename, $match) { // doesn't show if 1st char is _
        echo "$filename size " . filesize($filename) . "\n";
    }
}

but instead use glob()'s own regex to avoid loading unnecessary files in the first place, assuming this will be faster.

Upvotes: 3

Views: 3674

Answers (2)

Dave
Dave

Reputation: 3658

This'll do it.

$dir = glob("[!_]*.txt");
foreach ($dir as $filename) {
    echo "$filename size " . filesize($filename) . "<br />";
}

Upvotes: 14

ThiefMaster
ThiefMaster

Reputation: 318578

No need for a regex.

$files = array_filter(glob('*.txt'), function ($filename) {
  return $filename[0] != '_';
});

Upvotes: 6

Related Questions