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.
- pattern : It is a mandatory parameter which specifies the pattern to search for.
- string : It is a mandatory parameter which specifies the string or file to be checked.
- 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:
- The buffer must be cleared if the fnmatch() function is used multiple times.
- 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
<?php $check = "gfg.txt"; // fnmatch function used to check for file starting with g if ( fnmatch ("*[g]*", $check )) { echo "gfg"; } else { echo "match not found"; } ?> |
Output:
gfg
Program 2
php
<?php $check = "neveropen"; // fnmatch function used to check for // a word practice or practise if ( fnmatch ("*Geeks[gfgj]orGeeks", $check )) echo "Yes"; else echo "No"; ?> |
Yes
Program 3
php
<?php $check = 'GFG A computer science portal' ; // fnmatch function used to check // for a word php without considering its case if ( fnmatch ("*[PUTgfg]*", $check , FNM_CASEFOLD)) echo "Yes"; else echo "No"; ?> |
Yes
Program 4
php
<?php $check = "There is a back slash \ in this sentence"; // fnmatch function used to check for a \ if ( fnmatch ("*[\]*", $check , FNM_NOESCAPE)) echo "back slash (\) in the sentence "; else echo "match not found"; ?> |
back slash (\) in the sentence