I'm reading all the files in a single directory and I want to filter on JPG,JPEG,GIF and PNG.
Both capital and small letters. Those are the only files to be accepted.
I am currently using this:
$testPics = takeFiles($picsDir, "([^\s]+(?=\.(jpg|JPG|jpeg|JPEG|png|PNG|gif|GIF))\.\2)");
and the function takeFiles looks like this:
function takerFiles($dir, $rex="") {
$dir .= "/";
$files = array();
$dp = opendir($dir);
while ($file = readdir($dp)) {
if ($file == '.') continue;
if ($file == '..') continue;
if (is_dir($file)) continue;
if ($rex!="" && !preg_match($rex, $file)) continue;
$files[] = $file;
}
closedir($dp);
return $files;
}
And it always returns nothing. So something must be wrong with my regex code.
There are a few ways of doing this.
Have you tried glob()?:
Have you considered pathinfo()?:
If you're insistant upon using the regular expression, there's no need to match the whole filename, just the extension. Use the
$
token to match the end of the string, and use thei
flag to denote case-insensitivity. Also, don't forget to use a delimiter in your expression, in my case "%":Here are two different ways to compile an array of files by type (conf for demo) from a target directory. I'm not sure which is better performance wise.
This will return the full file path not just the file name
How about using glob() instead?
I think something is wrong with your regex. Try testing regexes here first: https://www.regexpal.com/
I think this one might work for you:
/^.*\.(jpg|jpeg|png|gif)$/i
Note the /i at the end - this is the "case insensitive" flag, saves you having to type out all permutations :)
This works out for me
Best.
You should put slashes around your regexp. -> "/(...)/"