matching multiple file extensions with fnmatch()
In the typical file matching code:
while (false !== ($file = readdir($handle))) {
if ($file !== "." && $file !== ".." && fnmatch($mask, $file)) {
$dirList[] = $file;
}
}
I was trying to use a multiple file extension pattern like this:
$mask = "*.{jpg,png,gif}";
but it doesn't work. No files match. This is rather strange since 开发者_运维百科the same pattern works just fine in a terminal. It also works perfectly well with glob(), returning the files I want. I know there's nothing wrong with the rest of the code because using "*.jpg" as mask also works with fnmatch. Wasn't fnmatch supposed to support the same patterns that are available in a shell?
It's not supported.
AFAIK the *.{ext,alt}
is an ksh and bash extension to shell globs. And fnmatch()
is a system function, but functionality varies among Unix variants (BSD has it, Linux/glibc seemingly doesn't). There exists an FNM_EXTMATCH
constant which I believe would allow {alt}
to work. But PHP doesn't support it / pass it on.
But you could just use glob()
with the GLOB_BRACE
option, which supports said .{jpeg,png,gif}
matching. And by this you'll save yourself an readdir().
Your curly bracket notation is what I'd expect to work on bash, but the fnmatch() call fails for me as well (as does the square bracket suggestion). If you look at the discussion about windows compatibility for this function (under its definition) at php.net you'll see that the curly bracket notation is not considered for the regex implementation of the function.
精彩评论