tags:

views:

127

answers:

5

would be nice if someone could give me a regexp pattern for glob for getting below filenames:

1.jpg // this file
1_thumb.jpg
2.png // this file
2_thumb.png
etc...

just returning the files without "_thumb". cause i got this regexp:

$numericalFiles = glob("$this->path/*_thumb.*");

and that give me all with "_thumb."

thanks

+2  A: 

Glob patterns and regular expressions are different. But PHP's glob implementation does not implement the pattern negation required for matching just those files. You will need to use a larger positive pattern such as [0-9]*.jpg and then filter the results afterwards.

Ignacio Vazquez-Abrams
A: 

Here you go:

glob($this->path . '/{0,1,2,3,4,5,6,7,8,9}.*', GLOB_BRACE);
Alix Axel
+2  A: 
foreach (glob('[0-9]*') as $filename) {
    if (strpos("$filename","_thumb") === FALSE){
        echo "$filename \n";
    }
}
ghostdog74
+2  A: 

glob() isn't the greatest at handling situations where you have complex requirements for file matching, as you've clearly noticed. I'd recommend using PHP's SPL library and taking advantage of the DirectoryIterator class.

$iterator = new DirectoryIterator("/dir/path");
foreach ($iterator as $file) {
    if ($file->isFile() && preg_match("/^[0-9]+\./i",$file->getFilename())) {
        echo $file->getFilename();
    }
}

You can modify your criteria cleanly during the iteration (also, it's easy to modify the iterator if you ever needed recursive directory iteration).

zombat
But it *is* possible that `glob()` could be handled by the libc, so starting with it means that you'll iterate through fewer results in the much slower PHP.
Ignacio Vazquez-Abrams
+1  A: 

Further to zombat's use of the DirectoryIterator, it might also make sense to construct your own specialized filter class to make life easier (see the difference with the foreach loops) and more reusable.

class DirectoryFilterThumbs extends FilterIterator {
    public function __construct($path) {
        parent::__construct(new DirectoryIterator($path));
    }
    public function accept() {
        // Use regex or whatever you like here
        return ($this->isFile() && strpos($this->getFilename(), "_thumb.") === FALSE);
    }
}

$files = new DirectoryFilterThumbs("/dir/path");
foreach ($files as $file) {
    echo $file->getFilename() . PHP_EOL;
}

Of course, if there is no need to do this in multiple places then the plain DirectoryIterator/condition combo given by zombat is perfectly suitable.

salathe