PHP検索フォルダ内のファイルUsing PHP's glob()function to find files in a directory

8644 ワード

Example directory
The examples below look at a directory with the following, the same example directory as used in the read through directory post:
bar.txt       A regular file
baz           A directory
foo.txt       A regular file
link2foo.txt  A symbolic link to foo.txt

Simple example
To find all the files in the directory/path/to/directory with a .txt file extension, you can do this:
$files = glob("/path/to/directory/*.txt");

The $files array contains the following from the example directory:
Array
(
    [0] => /path/to/directory/bar.txt
    [1] => /path/to/directory/foo.txt
    [2] => /path/to/directory/link2foo.txt
)

If no files matched the pattern then the array will be empty.
Example using braces
There are flags which can be passed as a second optional parameter. One of these is GLOB_BRACE which means that e.g. {jpg,gif,png} will be expanded to match jpg, gif and png which can be useful if you need to look for a particular set of files by their extension, in this example for image files.
If the example directory also had the files 1.jpg, 2.gif and 3.png then you can do this to get glob to return just the image files:
$files = glob("/path/to/directory/*.{jpg,gif,png}", GLOB_BRACE);

print_r($files) would echo:
Array
(
    [0] => /path/to/directory/1.jpg
    [1] => /path/to/directory/2.gif
    [2] => /path/to/directory/3.png
)

定義と使用法
glob()関数は、指定したモードに一致するファイル名またはディレクトリを返します.
この関数は、一致するファイル/ディレクトリを含む配列を返します.エラーが発生した場合falseを返します.
 
構文
glob(pattern,flags)
パラメータの説明
file
必要です.検索モードを指定します.
size
オプション.特殊な設定を定める.
  • GLOB_MARK-返される各アイテムに斜線
  • を追加
  • GLOB_NOSORT-ディレクトリにファイルが表示された元の順序で
  • を返します(ソートしません).
  • GLOB_NOCHECK-ファイルが一致しない場合は、検索用のパターン
  • を返す
  • GLOB_NOESCAPE-アンチスロープ符号
  • GLOB_BRACE-拡張{a,b,c}は、'a','b'または'c'
  • に一致する.
  • GLOB_ONLYDIR-パターンに一致するディレクトリエントリ
  • のみを返します.
  • GLOB_ERR-エラー情報(読み取り不能ディレクトリなど)を停止して読み取り、デフォルトではすべてのエラー
  • を無視します.
    注記:GLOB_ERRはPHP 5.1に追加されています.
    利用パラメータGLOB_BRACEは検索できます.インスタンス:
    <?php
    foreach (glob("*.txt") as $filename) {
        echo "$filename size " . filesize($filename) . " ";
    }
    ?>

     
     
    ディレクトリの下にあるすべてのサブディレクトリを取得
    <?php
    function listdirs($dir) {
       static $alldirs = array();
       $dirs = glob($dir . '/*', GLOB_ONLYDIR);
       if (count($dirs) > 0) {
           foreach ($dirs as $d) $alldirs[] = $d;
       }
       foreach ($dirs as $dir) listdirs($dir);
       return $alldirs;
    }
    ?>

     
     
    すべてのファイルに一致
    <?php
    $files = glob('{,.}*', GLOB_BRACE);
    ?>

     
     
    互換性のある大文字と小文字のマッチングを実現
    <?php
    $pattern = sql_case("*.pdf");
    var_dump(glob($pattern));
    ?>

     
     
    次のように類似しています.
    <?php
    foreach (array_merge(glob("*.pdf"),glob("*.PDF")) as $filename) {
         echo "$filename n";
    }
    ?>

     
     
    ディレクトリの下に一致します.txt接尾辞のファイル
    <?php
    foreach (glob("*.txt") as $filename) {
        echo $filename;
    }
    ?>

     
     
     
    注意事項
    1,リモートファイルには機能せず,チェックされたファイルはサーバのファイルシステムからアクセスしなければならない.
    2、glob(「[myfolder]/*.txt」)を使用すると一致しません.解決方法はglob(「[myfolder]/*.txt」)で、[]文字の適用に注意してください.
    3,次に2番目のパラメータflags有効フラグ説明(1)GLOB_MARK-返される各アイテムに斜線(2)GLOB_を追加NOSORT-ファイルがディレクトリに表示された元の順序で戻る(ソートしない)(3)GLOB_NOCHECK-ファイルが一致しない場合は検索用のモード(4)GLOB_を返すNOESCAPE-アンチスロープ符号(5)GLOB_BRACE-拡張{a,b,c}は'a','b'または'c'(6)GLOB_に一致するONLYDIR-パターンに一致するディレクトリ項目のみを返します注意:PHP 4.3.3バージョンより前にGLOB_ONLYDIRは、WindowsまたはGNU Cライブラリを使用しない他のシステムでは使用できません.(7)GLOB_ERR-読み取り不能ディレクトリなどのエラー情報の読み取りを停止し、デフォルトではすべてのエラー注意を無視します:GLOB_ERRはPHP 5.1に追加されています.
    glob()関数の典型的な応用は、あるディレクトリの下に取得するなどのデータテーブルファイルを読み取ることである.sql接尾辞ファイル、このようなユニットテストの中でとても実用的で、sqlファイルを読み取ることができてデータベースを再建するなどを実現することができて、具体的にPHPマニュアルに参加して、次の期のPHP内蔵関数の研究シリーズに注目してください
     
    What's in a pattern?
    Most people who have already encountered glob know to make use of the * metacharacter to match some characters, and those digging a little deeper often discover that discrete alternatives can be globbed with braces (e.g. image.{gif,jpg,png} ). However, there are more special characters and sequences that can be used to be more (or less, if we want) specific about what to find.
    Aside: please do not make the mistake of thinking that glob patterns are regular expressions, they're just not. If you do want to use regular expressions to find paths/files then you are invited to use SPL's RegexIterator, which allows filtering of an Iterator based on a PCRE regex, in conjunction with a DirectoryIterator or FilesystemIterator (there are recursive flavours of the Regex- and DirectoryIterator if you need to delve into folders). For those SPL-ly inclined, also note the [GlobIterator][globitertor] which combines the goodness of globbing with iteration. If that made entirely no sense, please read on! Globs are much less verbose.
    So, here are the special doohickeys (technical term!) that we can use with glob : * (an asterisk)
    Matches zero of more characters. ?
    Matches exactly any one character. [...]
    Matches one character from a group. A group can be a list of characters, e.g. [afkp] , or a range of characters, e.g. [a-g] which is the same as [abcdefg] . [!...]
    Matches any single character not in the group. [!a-zA-Z0-9] matches any character that is not alphanumeric. \
    Escapes the next character. For special characters, this causes them to not be treated as special. For example, \[ matches a literal [. If flags includes GLOB_NOESCAPE, this quoting is disabled and \ is handled as a simple character.
     
    Globbingly good glob examples
    Here are a few examples of what globs might look like alongside a brief description of the intended behaviour: if you have any suggestions please do make them in the comments as I'm running short on inspiration!
    pattern description *.txt
    Get directory contents which have the extension of.txt(Note: a file could be named simply.txt!). ??
    Get directory contents with names _exactly_ two characters in length. ??*
    Get directory contents with names _at least_ two characters in length. g?*
    Get directory contents with names at least two characters in length and starting with the letterg *.{jpg,gif,png}
    Get directory contents with an extension of.jpg,.gifor.png. Remember to use the GLOB_BRACE flag. DN?????.dat
    Get directory contents which start with the lettersDN, followed by five characters, with an extension of.dat. DN[0-9][0-9][0-9][0-9][0-9].dat
    Get directory contents which start with the lettersDN, followed by five _digits_, with an extension of.dat. [!aeiou]*
    Get directory contents which do not start with a vowel letter. [!a-d]*
    Get directory contents which do not start witha,b,cord. *\[[0-9]\].*
    Get directory contents whose basename ends with a single digit enclosed in square braces. If GLOB_NOESCAPE is used, a single digit enclosed in\[and\]which would be a pretty weird name. subdir/img*/th_?*
    Get directory contents whose name starts withth_(with at least one character after that) within directories whose names start withimgin thesubdirdirectory.
    Well there we go, I've said what I came here to say so all that remains to be done is give some link love to those two recent articles that prompted me to dust off this draft and click the "publish"button.
     
     
    原文/転自:PHP検索フォルダ内のファイルUsing PHP's glob()function to find files in a directory