Sunday, November 17, 2024
Google search engine
HomeLanguagesPHP | fnmatch( ) Function

PHP | fnmatch( ) Function

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




<?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";
?>


Output:

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";
 
 
?>


Output:

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";
?>


Output:

back slash  (\)  in the sentence

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

Dominic Rubhabha-Wardslaus
Dominic Rubhabha-Wardslaushttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Recent Comments