fnmatch

(PHP 4 >= 4.3.0, PHP 5, PHP 7, PHP 8)

fnmatchПроверяет совпадение имени файла с шаблоном

Описание

fnmatch(string $pattern, string $filename, int $flags = 0): bool

Функция fnmatch() проверяет, совпадает ли название файла или строка filename с шаблоном pattern, который состоит из подстановочных знаков командной оболочки.

Список параметров

pattern

Шаблон pattern, с которым нужно сопоставить. Часто аргумент pattern будет содержать подстановочные знаки вроде «?» и «*».

Подстановочные знаки параметра pattern
Подстановочный знак Описание
? Вопросительный знак будет соответствовать любому отдельному символу. Например, шаблон «file?.txt» будет соответствовать названиям файлов «file1.txt» и «fileA.txt», но не будет соответствовать названию файла «file10.txt».
* Звёздочка будет соответствовать нулю или нескольким символам. Например, шаблон «foo*.xml» будет соответствовать названиям файлов «foo.xml» или «foobar.xml».
[ ] Квадратные скобки создают диапазон кодовых точек кодировки ASCII или набор символов. Например, шаблон «index.php[45]» будет соответствовать названиям файлов «index.php4» и «index.php5», но не будет соответствовать названию файла «index.phpt». Диапазоны, которыми часто пользуются, — [0-9], [a-z] и [A-Z]. Разрешено указывать больше одного набора или диапазона одновременно, например [0-9a-zABC].
! Восклицательный знак указывают для совпадения с символами, которых нет в квадратных скобках. Например, шаблон «[!A-Z]*.html» будет соответствовать названию файла «demo.html», но не будет соответствовать названию «Demo.html».
\ Обратный слеш экранирует специальные символы. Например, шаблон «Name\?» будет соответствовать строке «Name?», не будет соответствовать строке «Names».

filename

Проверяемая строка. Функцией часто проверяют имена файлов, но также проверяют строки.

Среднеподготовленные посетители сайтов пользуются шаблонами командной оболочки или хотя бы несложными формами подстановок вроде «?» и «*». Поэтому для сопоставления поискового выражения, которое в пользовательской части сайта вводят незнакомые с программированием пользователи, вместо функции preg_match() лучше пользоваться функцией fnmatch().

flags

Параметр flags принимает комбинации следующих флагов, которые объединяют двоичным оператором ИЛИ (|).

Список возможных флагов для функции fnmatch()
Флаг Описание
FNM_NOESCAPE Отключить экранирование обратным слешем.
FNM_PATHNAME Слеш в строке совпадает только со слешем в шаблоне.
FNM_PERIOD Ведущая точка в строке должна точно совпадать с точкой в шаблоне.
FNM_CASEFOLD Совпадение без учёта регистра. Часть расширения GNU.

Возвращаемые значения

Функция возвращает true при совпадении, иначе false.

Примеры

Пример #1 Проверка соответствия названия цвета шаблону подстановки командной оболочки

<?php

if (fnmatch("*gr[ae]y", $color)) {
echo
"Какая-то форма серого цвета...";
}

?>

Примечания

Внимание

Функция пока недоступна на POSIX-несовместимых системах, кроме Windows.

Смотрите также

  • glob() - Находит файловые пути, совпадающие с шаблоном
  • preg_match() - Выполняет проверку на соответствие регулярному выражению
  • sscanf() - Разбирает строку в соответствии с заданным форматом
  • printf() - Выводит отформатированную строку
  • sprintf() - Возвращает отформатированную строку

add a note add a note

User Contributed Notes 9 notes

up
10
me at rowanlewis dot com
13 years ago
Here's a definitive solution, which supports negative character classes and the four documented flags.

<?php
   
   
if (!function_exists('fnmatch')) {
       
define('FNM_PATHNAME', 1);
       
define('FNM_NOESCAPE', 2);
       
define('FNM_PERIOD', 4);
       
define('FNM_CASEFOLD', 16);
       
        function
fnmatch($pattern, $string, $flags = 0) {
            return
pcre_fnmatch($pattern, $string, $flags);
        }
    }
   
    function
pcre_fnmatch($pattern, $string, $flags = 0) {
       
$modifiers = null;
       
$transforms = array(
           
'\*'    => '.*',
           
'\?'    => '.',
           
'\[\!'    => '[^',
           
'\['    => '[',
           
'\]'    => ']',
           
'\.'    => '\.',
           
'\\'    => '\\\\'
       
);
       
       
// Forward slash in string must be in pattern:
       
if ($flags & FNM_PATHNAME) {
           
$transforms['\*'] = '[^/]*';
        }
       
       
// Back slash should not be escaped:
       
if ($flags & FNM_NOESCAPE) {
            unset(
$transforms['\\']);
        }
       
       
// Perform case insensitive match:
       
if ($flags & FNM_CASEFOLD) {
           
$modifiers .= 'i';
        }
       
       
// Period at start must be the same as pattern:
       
if ($flags & FNM_PERIOD) {
            if (
strpos($string, '.') === 0 && strpos($pattern, '.') !== 0) return false;
        }
       
       
$pattern = '#^'
           
. strtr(preg_quote($pattern, '#'), $transforms)
            .
'$#'
           
. $modifiers;
       
        return (boolean)
preg_match($pattern, $string);
    }
   
?>

This probably needs further testing, but it seems to function identically to the native fnmatch implementation.
up
2
bernd dot ebert at gmx dot net
11 years ago
There is a problem within the  pcre_fnmatch-Function concerning backslashes. Those will be masked by preq_quote and ADDITONALLY by the strtr if FN_NOESCAPE is not set -> something like "*a(*" will finally result in "#^.*a\\(.*$#". Note the double backslash which effectively does NOT mask the "(" correctly.

Since preq_quote always matches a backslash I don't think that this'll work with using preg_quote at all.
up
1
Sinured
15 years ago
An addition to my previous note: My statement regarding the FNM_* constants was wrong. They are available on POSIX-compliant systems (in other words, if fnmatch() is defined).
up
0
Frederik Krautwald
16 years ago
soywiz's function still doesn't seem to work -- at least not with PHP 5.2.3 on Windows -- but jk's does.
up
0
jk at ricochetsolutions dot com
17 years ago
soywiz's function didnt seem to work for me, but this did.

<?php
if(!function_exists('fnmatch')) {

    function
fnmatch($pattern, $string) {
        return
preg_match("#^".strtr(preg_quote($pattern, '#'), array('\*' => '.*', '\?' => '.'))."$#i", $string);
    }
// end

} // end if
?>
up
0
phlipping at yahoo dot com
20 years ago
you couls also try this function that I wrote before I found fnmatch:

function WildToReg($str)
{
  $s = "";  
  for ($i = 0; $i < strlen($str); $i++)
  {
   $c = $str{$i};
   if ($c =='?')
    $s .= '.'; // any character
   else if ($c == '*')   
    $s .= '.*'; // 0 or more any characters   
   else if ($c == '[' || $c == ']')
    $s .= $c;  // one of characters within []
   else
    $s .= '\\' . $c;
  }
  $s = '^' . $s . '$';

  //trim redundant ^ or $
  //eg ^.*\.txt$ matches exactly the same as \.txt$
  if (substr($s,0,3) == "^.*")
   $s = substr($s,3);
  if (substr($s,-3,3) == ".*$")
   $s = substr($s,0,-3);
  return $s;
}

if (ereg(WildToReg("*.txt"), $fn))
  print "$fn is a text file";
else
  print "$fn is not a text file";
up
-2
theboydanny at gmail dot com
16 years ago
About the windows compat functions below:
I needed fnmatch for a application that had to work on Windows, took a look here and tested both. Jk's works for me, soywiz didn't (on WinXPSP2, PHP 5.2.3).
The only difference between them is addcslashes (soywiz) instead of preg_quote (jk). They _should_ both work, but for some reason soywiz's didn't for me. So YMMV.
However, to make JK's fnmatch() work with the example in the documentation, you also have to strtr the [ and ] in $pattern.
<?php
$pattern
= strtr(preg_quote($pattern, '#'), array('\*' => '.*', '\?' => '.', '\[' => '[', '\]' => ']'));
?>
And thanks for the functions, guys.
up
-4
Sinured
16 years ago
Possible flags (scratched out of fnmatch.h):
...::...

FNM_PATHNAME:
> Slash in $string only matches slash in $pattern.

FNM_PERIOD:
> Leading period in $string must be exactly matched by period in $pattern.

FNM_NOESCAPE:
> Disable backslash escaping.

FNM_NOSYS:
> Obsolescent.

FNM_FILE_NAME:
> Alias of FNM_PATHNAME.

FNM_LEADING_DIR:
> From fnmatch.h: /* Ignore `/...' after a match.  */

FNM_CASEFOLD:
> Caseless match.

Since they’re appearing in file.c, but are not available in PHP, we’ll have to define them ourselves:
<?php
define
('FNM_PATHNAME', 1);
define('FNM_PERIOD', 4);
define('FNM_NOESCAPE', 2);
// GNU extensions
define('FNM_FILE_NAME', FNM_PATHNAME);
define('FNM_LEADING_DIR', 8);
define('FNM_CASEFOLD', 16);
?>

I didn’t test any of these except casefold, which worked for me.
up
-11
bwilcock at gmail dot com
10 years ago
fnmatch is not 100% reliable. Bug 14185 is still open and may or may not have been patched.

In certain wildcard circumstance fnmatch("*needle*", $haystack, match) returns false intermittantly

However stripos or preg returns a "find".
To Top