downloads | documentation | faq | getting help | mailing lists | licenses | wiki | reporting bugs | php.net sites | links | conferences | my php.net

search for in the

fopen> <flock
Last updated: Fri, 19 Feb 2010

view this page in

fnmatch

(PHP 4 >= 4.3.0, PHP 5)

fnmatchファイル名がパターンにマッチするか調べる

説明

bool fnmatch ( string $pattern , string $string [, int $flags = 0 ] )

fnmatch()string で指定された文字列が pattern で指定されたシェルワイルドカードにマッチするかどうかチェックします。

パラメータ

pattern

シェルのワイルドカードパターン。

string

調べたい文字列。この機能は特にファイル名のマッチに便利ですが、 通常の文字列に関しても使用できます。

一般的なユーザにとって、シェルパターンやあるいは少なくとも '?''*'によるワイルドカードのほうが 慣れていると思われます。そのため、 preg_match() の代わりに fnmatch() をフロントエンドの検索表現として使うことは、 プログラマではないユーザにとってより便利でしょう。

flags

FNM_XXX 定数のいずれか。

返り値

マッチした場合に TRUE、それ以外の場合に FALSE を返します。

変更履歴

バージョン 説明
5.3.0 この関数は Windows プラットフォームでも動作するようになりました。

例1 シェルのワイルドカードパターンによる色の名前のチェック

<?php
if (fnmatch("*gr[ae]y"$color)) {
  echo 
"some form of gray ...";
}
?>

注意

警告

今のところ、この機能は POSIX に準拠していないシステムで利用できません。

参考

  • glob() - パターンにマッチするパス名を探す
  • preg_match() - 正規表現によるマッチングを行う
  • sscanf() - フォーマット文字列に基づき入力を処理する
  • printf() - フォーマット済みの文字列を出力する
  • sprintf() - フォーマットされた文字列を返す



fopen> <flock
Last updated: Fri, 19 Feb 2010
 
add a note add a note User Contributed Notes
fnmatch
Sinured
19-Mar-2008 09:04
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).
theboydanny at gmail dot com
29-Nov-2007 06:31
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.
Sinured
30-Jul-2007 05:14
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.
Frederik Krautwald
12-Jun-2007 05:30
soywiz's function still doesn't seem to work -- at least not with PHP 5.2.3 on Windows -- but jk's does.
soywiz at NOSPAM dot php dot net
21-Jan-2007 03:40
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
           
);
        }
    }
?>
jk at ricochetsolutions dot com
13-Dec-2006 01:39
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 at php dot net
18-Jul-2006 02:12
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);
        }
    }
?>
jsnell at networkninja dot com
03-Mar-2006 03:12
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.
soywiz at gmail dot com
26-Jul-2005 11:07
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);
}
}
?>
phlipping at yahoo dot com
06-Aug-2003 10:59
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";

fopen> <flock
Last updated: Fri, 19 Feb 2010
 
 
show source | credits | sitemap | contact | advertising | mirror sites