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.
fnmatch
(PHP 4 >= 4.3.0, PHP 5)
fnmatch — Dosya ismi belirtilen kalıpla eşleşiyor mu diye bakar
Açıklama
$kalıp
, string $dizge
[, int $seçenekler = 0
] )
fnmatch() işlevi, belirtilen
dizge'nin belirtilen dosya kalıbı ile eşleşip
eşleşmediğine bakar.
Değiştirgeler
-
kalıp -
Kabuk dosya ismi kalıbı.
-
dizge -
Sınanacak dizge. İşlev özellikle dosya isimleri için yararlı olsa da sıradan dizgeler için de kullanılabilir.
Ortalama bir kullanıcı, kabuk dosya ismi kalıplarını veya bunların en basit biçimleri olan '?' ve '*' karakterlerini kullanabilir. Bu bakımdan, programcı olmayan kullanıcılar için preg_match() yerine fnmatch() kullanımı daha uygun olabilir.
-
seçenekler -
Belirtilebilecek seçenekler:
fnmatch() işlevinin seçeneklerdeğiştirgesinde belirtilebilecek seçeneklerSeçenekAçıklama FNM_NOESCAPE \ karakteri kalıplarda özel olarak ele alınmaz. Normalde, \ kendinden sonraki karakteri önceler; bu seçenek etkinse bu özellik kapatılır, böylece sadece kendisiyle eşleşebilir. Önceleme etkin olduğunda, \? kalıbı sadece ? karakteri ile eşleşir, çünkü kalıp içindeki soru işareti sıradan bir karakter gibi işlem görür. Eğer FNM_NOESCAPE seçeneği etkinse, \ sıradan bir karakterdir. FNM_PATHNAME Bu POSIX.2 ile gelen bir FNM_FILE_NAME takma ismidir. FNM_PERIOD . karakteri dosya isimlerinin başında ise özel olarak ele alınır. Bu seçenek etkinse ve . karakteri
dizgedizgesinin ilk karakteri ise kalıp ile eşleşemez.FNM_PERIOD ve FNM_FILE_NAME birlikte belirtilmişse, . karakterinin
dizgedizgesinin başında olmasının yanında / karakterini izlediği durumda da eşleşme sağlanır. (Kabuk FNM_PERIOD ve FNM_FILE_NAME seçeneklerini dosya isimleriyle eşleşme ararken birlikte kullanır.)FNM_CASEFOLD dizgeilekalıpkarşılaştırılırken harf büyüklüğüne bakılmaz.
Dönen Değerler
Eşleşme sağlanmışsa TRUE aksi takdirde FALSE.
Sürüm Bilgisi
| Sürüm: | Açıklama |
|---|---|
| 5.3.0 | İşlev Windows platformlarında da kullanılabilir oldu. |
Örnekler
Örnek 1 - Bir renk isminin bir kabuk dosya kalıbıyla eşleştirilmesi
<?php
if (fnmatch("*gr[ae]y", $color)) {
echo "some form of gray ...";
}
?>
Notlar
Bu işlev şimdilik POSIX uyumlu olmayan sistemlerde kullanılamamaktadır.
Ayrıca Bakınız
- glob() - Bir kalıpla eşleşen dosya yollarını bulur
- preg_match() - Bir düzenli ifadeyi eşleştirmeye çalışır
- sscanf() - Girdi dizgesini belli bir biçeme göre yorumlar
- printf() - Biçemli bir dizge çıktılar
- sprintf() - Biçemli bir dizge döndürür
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
?>
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.
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.
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).
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.
soywiz's function still doesn't seem to work -- at least not with PHP 5.2.3 on Windows -- but jk's does.
A revised better alternative for fnmatch on windows. It should work well on PHP >= 4.0.0
<?php
if (!function_exists('fnmatch')) {
function fnmatch($pattern, $string) {
return @preg_match(
'/^' . strtr(addcslashes($pattern, '/\\.+^$(){}=!<>|'),
array('*' => '.*', '?' => '.?')) . '$/i', $string
);
}
}
?>
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";
A better "fnmatch" alternative for windows that converts a fnmatch pattern into a preg one. It should work on PHP >= 4.0.0
<?php
if (!function_exists('fnmatch')) {
function fnmatch($pattern, $string) {
return @preg_match('/^' . strtr(addcslashes($pattern, '\\.+^$(){}=!<>|'), array('*' => '.*', '?' => '.?')) . '$/i', $string);
}
}
?>
The last line of soywiz at gmail dot com windows replacement should be changed to:
return preg_match('/' . $npattern . '$/i', $string);
otherwise, a pattern for *.xml will match file.xml~ or any else anything with the text *.xml in it, regardless of position.
A "fnmatch" alternative that converts the pattern, to a valid preg one and uses preg_match then. It will work on windows.
<?php
if (!function_exists('fnmatch')) {
function fnmatch($pattern, $string) {
for ($op = 0, $npattern = '', $n = 0, $l = strlen($pattern); $n < $l; $n++) {
switch ($c = $pattern[$n]) {
case '\\':
$npattern .= '\\' . @$pattern[++$n];
break;
case '.': case '+': case '^': case '$': case '(': case ')': case '{': case '}': case '=': case '!': case '<': case '>': case '|':
$npattern .= '\\' . $c;
break;
case '?': case '*':
$npattern .= '.' . $c;
break;
case '[': case ']': default:
$npattern .= $c;
if ($c == '[') {
$op++;
} else if ($c == ']') {
if ($op == 0) return false;
$op--;
}
break;
}
}
if ($op != 0) return false;
return preg_match('/' . $npattern . '/i', $string);
}
}
?>
