CascadiaPHP 2024


(PHP 4 >= 4.3.0, PHP 5, PHP 7, PHP 8)

fnmatchMatch filename against a pattern


fnmatch(string $pattern, string $filename, int $flags = 0): bool

fnmatch() checks if the passed filename would match the given shell wildcard pattern.

Elenco dei parametri


The pattern to match against. Usually, the pattern will contain wildcards like '?' and '*'.

Wildcards to be used in pattern parameter
Wildcard Descrizione
? Question mark will match any single character. For example, pattern "file?.txt" will match "file1.txt" and "fileA.txt", but will not match "file10.txt".
* Asterisk will match zero or more characters. For example, pattern "foo*.xml" will match "foo.xml" and "foobar.xml".
[ ] Square brackets are used to create ranges of ASCII codepoints or sets of characters. For example, pattern "index.php[45]" will match "index.php4" and "index.php5", but will not match "index.phpt". Well known ranges are [0-9], [a-z], and [A-Z]. Multiple sets and ranges can be used at the same time, for example [0-9a-zABC].
! Exclamation mark is used to negate characters within square brackets. For example, "[!A-Z]*.html" will match "demo.html", but will not match "Demo.html".
\ Backslash is used to escape special characters. For example, "Name\?" will match "Name?", but will not match "Names".


The tested string. This function is especially useful for filenames, but may also be used on regular strings.

The average user may be used to shell patterns or at least in their simplest form to '?' and '*' wildcards so using fnmatch() instead of preg_match() for frontend search expression input may be way more convenient for non-programming users.


The value of flags can be any combination of the following flags, joined with the binary OR (|) operator.

A list of possible flags for fnmatch()
Flag Description
FNM_NOESCAPE Disable backslash escaping.
FNM_PATHNAME Slash in string only matches slash in the given pattern.
FNM_PERIOD Leading period in string must be exactly matched by period in the given pattern.
FNM_CASEFOLD Caseless match. Part of the GNU extension.

Valori restituiti

Returns true if there is a match, false otherwise.


Example #1 Checking a color name against a shell wildcard pattern

if (fnmatch("*gr[ae]y", $color)) {
"some form of gray ...";



For now, this function is not available on non-POSIX compliant systems except Windows.

Vedere anche:

  • glob() - Find pathnames matching a pattern
  • preg_match() - Riconoscimento con espressioni regolari
  • sscanf() - Analizza l'input da una string in base al formato
  • printf() - Visualizza una stringa formattata
  • sprintf() - Restituisce una stringa formattata

add a note

User Contributed Notes 9 notes

me at rowanlewis dot com
13 years ago
Here's a definitive solution, which supports negative character classes and the four documented flags.


if (!function_exists('fnmatch')) {
define('FNM_PATHNAME', 1);
define('FNM_NOESCAPE', 2);
define('FNM_PERIOD', 4);
define('FNM_CASEFOLD', 16);

fnmatch($pattern, $string, $flags = 0) {
pcre_fnmatch($pattern, $string, $flags);

pcre_fnmatch($pattern, $string, $flags = 0) {
$modifiers = null;
$transforms = array(
'\*' => '.*',
'\?' => '.',
'\[\!' => '[^',
'\[' => '[',
'\]' => ']',
'\.' => '\.',
'\\' => '\\\\'

// Forward slash in string must be in pattern:
if ($flags & FNM_PATHNAME) {
$transforms['\*'] = '[^/]*';

// Back slash should not be escaped:
if ($flags & FNM_NOESCAPE) {

// Perform case insensitive match:
if ($flags & FNM_CASEFOLD) {
$modifiers .= 'i';

// Period at start must be the same as pattern:
if ($flags & FNM_PERIOD) {
if (
strpos($string, '.') === 0 && strpos($pattern, '.') !== 0) return false;

$pattern = '#^'
. strtr(preg_quote($pattern, '#'), $transforms)
. $modifiers;

return (boolean)
preg_match($pattern, $string);


This probably needs further testing, but it seems to function identically to the native fnmatch implementation.
bernd dot ebert at gmx dot net
12 years ago
There is a problem within the pcre_fnmatch-Function concerning backslashes. Those will be masked by preq_quote and ADDITONALLY by the strtr if FN_NOESCAPE is not set -> something like "*a(*" will finally result in "#^.*a\\(.*$#". Note the double backslash which effectively does NOT mask the "(" correctly.

Since preq_quote always matches a backslash I don't think that this'll work with using preg_quote at all.
16 years ago
An addition to my previous note: My statement regarding the FNM_* constants was wrong. They are available on POSIX-compliant systems (in other words, if fnmatch() is defined).
jk at ricochetsolutions dot com
17 years ago
soywiz's function didnt seem to work for me, but this did.

if(!function_exists('fnmatch')) {

fnmatch($pattern, $string) {
preg_match("#^".strtr(preg_quote($pattern, '#'), array('\*' => '.*', '\?' => '.'))."$#i", $string);
// end

} // end if
Frederik Krautwald
17 years ago
soywiz's function still doesn't seem to work -- at least not with PHP 5.2.3 on Windows -- but jk's does.
theboydanny at gmail dot com
16 years ago
About the windows compat functions below:
I needed fnmatch for a application that had to work on Windows, took a look here and tested both. Jk's works for me, soywiz didn't (on WinXPSP2, PHP 5.2.3).
The only difference between them is addcslashes (soywiz) instead of preg_quote (jk). They _should_ both work, but for some reason soywiz's didn't for me. So YMMV.
However, to make JK's fnmatch() work with the example in the documentation, you also have to strtr the [ and ] in $pattern.
= strtr(preg_quote($pattern, '#'), array('\*' => '.*', '\?' => '.', '\[' => '[', '\]' => ']'));
And thanks for the functions, guys.
phlipping at yahoo dot com
20 years ago
you couls also try this function that I wrote before I found fnmatch:

function WildToReg($str)
$s = "";
for ($i = 0; $i < strlen($str); $i++)
$c = $str{$i};
if ($c =='?')
$s .= '.'; // any character
else if ($c == '*')
$s .= '.*'; // 0 or more any characters
else if ($c == '[' || $c == ']')
$s .= $c; // one of characters within []
$s .= '\\' . $c;
$s = '^' . $s . '$';

//trim redundant ^ or $
//eg ^.*\.txt$ matches exactly the same as \.txt$
if (substr($s,0,3) == "^.*")
$s = substr($s,3);
if (substr($s,-3,3) == ".*$")
$s = substr($s,0,-3);
return $s;

if (ereg(WildToReg("*.txt"), $fn))
print "$fn is a text file";
print "$fn is not a text file";
16 years ago
Possible flags (scratched out of fnmatch.h):

> Slash in $string only matches slash in $pattern.

> Leading period in $string must be exactly matched by period in $pattern.

> Disable backslash escaping.

> Obsolescent.

> Alias of FNM_PATHNAME.

> From fnmatch.h: /* Ignore `/...' after a match. */

> Caseless match.

Since they’re appearing in file.c, but are not available in PHP, we’ll have to define them ourselves:
define('FNM_PERIOD', 4);
define('FNM_NOESCAPE', 2);
// GNU extensions
define('FNM_LEADING_DIR', 8);
define('FNM_CASEFOLD', 16);

I didn’t test any of these except casefold, which worked for me.
bwilcock at gmail dot com
10 years ago
fnmatch is not 100% reliable. Bug 14185 is still open and may or may not have been patched.

In certain wildcard circumstance fnmatch("*needle*", $haystack, match) returns false intermittantly

However stripos or preg returns a "find".
To Top