Reputation: 1041
So here is my problem.
I want to select only those files from the folder, which name contains only letters and numbers with specific file extensions.
Here is the pattern
$files = glob($somedir.'/[a-zA-Z0-9]{4,71}.{jpeg,png}',GLOB_BRACE);
When I print it out print_r($files)
it returns an empty array.
Is it possible to use regex with glob() and which part should I correct in my code?
If there is something I can improve in my question, let me know.
Upvotes: 0
Views: 171
Reputation: 212412
This is where SPL's iterators can be very useful as an alternative to glob(), allowing you to use a full regexp
class ImageFilterIterator extends FilterIterator {
// overwriting the accept method to perform a super simple test to
// determine if the files found were images (types we want at least) or
// not..
public function accept() {
if (preg_match('/^[a-z0-9]{4,71}\.(gif|jpe?g|png)$/i',$this->getExtension())) {
return true;
} else {
return false;
}
}
}
$path = dirname(__FILE__);
foreach(new ImageFilterIterator(new FilesystemIterator($path)) as $image) {
echo $image, PHP_EOL;
}
Upvotes: 1
Reputation: 13818
glob()
does not work with regular expressions, only with shell patterns - see its documentation. And they are limited.
You can use a loop instead along these lines:
$files = array();
$dir = opendir($somedir);
while (($fname = readdir($dir)) !== false) {
if (preg_match('/^[a-zA-Z0-9]{4,71}\.(jpeg|png)$/', $fname))
$files[] = "$somedir/$fname";
}
closedir($dir);
Upvotes: 0