HomeMenu
Jesus · Bible · HTML · CSS · JS · PHP · SVG · Applications

fnmatch

Description

The fnmatch of Filesystem for PHP match filename against a pattern.

Syntax

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

Parameters

pattern

The shell wildcard pattern.

filename

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.

flags

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

NumberConstantDescription
1FNM_PATHNAMESlash in string only matches slash in the given pattern.
2FNM_NOESCAPEDisable backslash escaping.
4FNM_PERIODLeading period in string must be exactly matched by period in the given pattern.
16FNM_CASEFOLDCaseless match. Part of the GNU extension.

Return

Returns true if there is a match, false otherwise.

Examples

1 · pattern filename

<?

$pattern = "gr[ae]y";
$filename = "gray";

$return = fnmatch($pattern, $filename);

var_export($return);
true

2 · flags · FNM_PATHNAME

<?

$pattern = "/*";
$filename = "/path/";
$flags = FNM_PATHNAME;

$return1 = fnmatch($pattern, $filename);
$return2 = fnmatch($pattern, $filename, $flags);

var_dump($return1, $return2);
bool(true)
bool(false)

3 · flags · FNM_NOESCAPE

<?

$pattern = "\\\\";
$filename = "\\";
$flags = FNM_NOESCAPE;

$return1 = fnmatch($pattern, $filename);
$return2 = fnmatch($pattern, $filename, $flags);

var_dump($return1, $return2);
bool(true)
bool(false)

4 · flags · FNM_PERIOD

<?

$pattern = "[\.]*";
$filename = ".";
$flags = FNM_PERIOD;

$return1 = fnmatch($pattern, $filename);
$return2 = fnmatch($pattern, $filename, $flags);

var_dump($return1, $return2);
bool(true)
bool(false)

5 · flags · FNM_CASEFOLD

<?

$pattern = "CASE";
$filename = "case";
$flags = FNM_CASEFOLD;

$return1 = fnmatch($pattern, $filename);
$return2 = fnmatch($pattern, $filename, $flags);

var_dump($return1, $return2);
bool(false)
bool(true)