PHP fnmatch() Function
The PHP fnmatch() function is used to check if a filename or string matches against a specified shell wildcard pattern. The function returns true if there is a match, false otherwise.
Syntax
fnmatch(pattern, string, flags)
Parameters
pattern |
Required. Specify the shell wildcard pattern to search for. |
string |
Required. Specify the string or filename to be checked. |
flags |
Optional. Specify the value of flag. It can be any combination of the following flags, joined with the binary OR (|) operator:
|
Return Value
Returns true if there is a match, false otherwise.
Example: checking a shell wildcard pattern in a string
The example below shows the usage of fnmatch() function.
<?php $str = "I have a black colored car."; $pattern = "*color*"; //checking for the pattern //in the given string if (fnmatch($pattern, $str)) echo "Match found"; else echo "Match not found"; ?>
The output of the above code will be:
Match found
Example: checking a color name against a shell wildcard pattern
In the example below , the fnmatch() function is used to check if the string contains grey or gray.
<?php $str = "I have a gray colored car."; $pattern = "*gr[ae]y*"; //checking for gray/grey //in the given string if (fnmatch($pattern, $str)) echo "Match found"; else echo "Match not found"; ?>
The output of the above code will be:
Match found
Example: Caseless match
The example below shows how to use flag parameter to perform caseless match using this function.
<?php $str = "I have a gray colored car."; $pattern = "*Gr[AE]y*"; //checking for grey/gray (caseless) //in the given string if (fnmatch($pattern, $str, FNM_CASEFOLD)) echo "Match found"; else echo "Match not found"; ?>
The output of the above code will be:
Match found
❮ PHP Filesystem Reference