fnmatch

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.

Number Name Description
1 FNM_PATHNAME Slash in string only matches slash in the given pattern.
2 FNM_NOESCAPE Disable backslash escaping.
4 FNM_PERIOD Leading period in string must be exactly matched by period in the given pattern.
16 FNM_CASEFOLD Caseless 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)

basename

chgrp

chmod

chown

clearstatcache

copy

dirname

disk_free_space

disk_total_space

diskfreespace

fclose

feof

fflush

fgetc

fgetcsv

fgets

file

file_exists

file_get_contents

file_put_contents

fileatime

filectime

filegroup

fileinode

filemtime

fileowner

fileperms

filesize

filetype

flock

fopen

fpassthru

fputcsv

fputs

fread

fscanf

fseek

fstat

ftell

ftruncate

fwrite

glob

is_dir

is_executable

is_file

is_link

is_readable

is_uploaded_file

is_writable

is_writeable

lchgrp

lchown

link

linkinfo

lstat

mkdir

move_uploaded_file

pathinfo

pclose

popen

readfile

readlink

realpath

realpath_cache_get

realpath_cache_size

rename

rewind

rmdir

set_file_buffer

stat

symlink

tempnam

tmpfile

touch

umask

unlink

PHP

Home Menu