PHP | fnmatch( ) Function (original) (raw)

Last Updated : 02 Jun, 2022

The fnmatch() function in PHP used to match a filename or string against a specified pattern. The pattern and the filename to be checked are sent as parameters to the fnmatch() function and it returns True if a match is found and False on failure. fnmatch() function is now available for Windows platforms on the PHP 5.3.0 version.

Syntax:

fnmatch(pattern, string, flags)

Parameters Used: The fnmatch() function in PHP accepts three parameter.

  1. pattern : It is a mandatory parameter which specifies the pattern to search for.
  2. string : It is a mandatory parameter which specifies the string or file to be checked.
  3. flags : It is an optional parameter which is used to specify flags or a combination of flags. The flags can be a combination of the following flags:
    • FNM_PATHNAME : It is used to specify slash in string only matches slash in the given pattern.
    • FNM_NOESCAPE : It is used to disable backslash escaping.
    • FNM_CASEFOLD : It is used for a caseless match.
    • FNM_PERIOD : It is used to specify a leading period in string must be exactly matched by period in the given pattern.

Return Value: It returns True if a match is found and a False on failure.

Errors And Exceptions:

  1. The buffer must be cleared if the fnmatch() function is used multiple times.
  2. The fnmatch() function returns Boolean False but many times it happens that it returns a non-Boolean value which evaluates to False.

Below programs illustrate the fnmatch() function.

Program 1 Suppose there is a file named "gfg.txt"

php `

`

Output:

gfg

Program 2

php `

`

Program 3

php `

`

Program 4

php `

`

Output:

back slash () in the sentence

Reference: http://php.net/manual/en/function.fnmatch.php