fnmatch
(PHP 4 >= 4.3.0, PHP 5)
fnmatch — Совпадает ли имя файла с шаблоном
Описание
fnmatch() проверяет, совпадает ли переданный параметр string с указанным шаблоном подстановок оболочки (shell wildcard) pattern .
Эта функция полезна при рабоде с именами файлов, хотя может быть использована и на обычной строке. Среднестатистический пользователь знаком с подстановками оболочки, как минимум в их простейшей форме из подстановок '?' и '*', так что использование fnmatch() вместо ereg() или preg_match() для поиска в пользовательской части сайта может быть намного удобнее для пользователей, не знакомых с регулярными выражениями.
Пример #1 Проверяет, соответствует ли цвет шаблону подстановок оболочки.
<?php
if (fnmatch("*gr[ae]y", $color)) {
echo "some form of gray ...";
}
?>
На данный момент эта функция недоступна в Windows и других POSIX-несовместимых системах.
См. также описание функций glob(), ereg(), preg_match() и Unix manpage по теме fnmatch(3) для получения информации относительно названий флагов (до тех пор, пока они не задокументированы здесь ).
- PHP Руководство
- Функции по категориям
- Индекс функций
- Справочник функций
- Расширения для работы с файловой системой
- Функции для работы с файловой системой
- basename
- chgrp
- chmod
- chown
- clearstatcache
- copy
- delete
- dirname
- disk_free_space
- disk_total_space
- diskfreespace
- fclose
- feof
- fflush
- fgetc
- fgetcsv
- fgets
- fgetss
- file_exists
- file_get_contents
- file_put_contents
- file
- fileatime
- filectime
- filegroup
- fileinode
- filemtime
- fileowner
- fileperms
- filesize
- filetype
- flock
- fnmatch
- fopen
- fpassthru
- fputcsv
- fputs
- fread
- fscanf
- fseek
- fstat
- ftell
- ftruncate
- fwrite
- glob
- is_dir
- is_executable
- is_file
- is_link
- is_readable
- is_uploaded_file
- is_writable
- is_writeable
- lchgrp
- lchown
- link
- linkinfo
- lstat
- mkdir
- move_uploaded_file
- parse_ini_file
- parse_ini_string
- pathinfo
- pclose
- popen
- readfile
- readlink
- realpath_cache_get
- realpath_cache_size
- realpath
- rename
- rewind
- rmdir
- set_file_buffer
- stat
- symlink
- tempnam
- tmpfile
- touch
- umask
- unlink
Коментарии
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";
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
?>
soywiz's function still doesn't seem to work -- at least not with PHP 5.2.3 on Windows -- but jk's does.
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.
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).
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.
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.