PHP 檔案系統 fnmatch() 函式



PHP 檔案系統fnmatch()函式用於將檔名或字串與給定模式匹配。該函式可以檢查給定字串是否與給定的 shell 萬用字元模式匹配。此函式未在 Windows 平臺上實現。

語法

以下是 PHP 檔案系統fnmatch()函式的語法:

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

引數

以下是fnmatch()函式的必填和可選引數:

序號 引數及說明
1

pattern(必填)

您要匹配的模式。這包括字元

  • * 匹配任意數量的字元。
  • ? 匹配恰好一個字元。
  • [] 匹配任何一個包含的字元。
  • 2

    string(必填)

    這是您要匹配的字串或檔名。

    3

    flags(必填)

    修改匹配行為的標誌。可能的值為:FNM_NOESCAPE、FNM_PATHNAME、FNM_PERIOD

    返回值

    如果匹配則返回 TRUE,失敗則返回 FALSE。

    PHP 版本

    fnmatch()函式首次作為 PHP 4.3.0 核心的一部分引入,並且與 PHP 5、PHP 7、PHP 8 良好相容。

    示例

    PHP 檔案系統fnmatch()函式返回一個布林值,可以是 TRUE 或 FALSE,您可以使用條件表示式(如 if 語句和三元運算子)來驗證這一點。檢視以下程式碼示例:

    <?php
       //Define pattern here to match
       $pattern = "*.txt";
       $string = "sample.txt";
    
       if (fnmatch($pattern, $string)) {
          echo "The string matches the pattern.";
       } else {
          echo "The string does not match the pattern.";
       }
    ?>
    

    輸出

    以下是上述 PHP 程式碼的輸出:

    The string matches the pattern.   
    

    示例

    這段程式碼根據字串“phpcodes.txt”是否與特定模式匹配建立一條訊息。將 $colour 與模式“*phpcode[zs].txt”比較後,`fnmatch() 函式返回結果:任何字元都匹配 *,檔名必須包含 phpcode,[zs] 表示 phpcode 必須在 z 或 s 之後,結尾必須是 .txt。

    <?php
       $color = "phpcodes.txt";
       if(fnmatch("*phpcode[zs].txt", $color)) {
          echo "phpcodes";
       } else {
          echo "Color not found!";
       }
    ?>
    

    輸出

    這將生成以下結果:

    phpcodes
    

    示例

    現在我們將使用 flags 引數來演示fnmatch()函式中的用法。例如,如果萬用字元 ? 匹配任何單個字元,則函式返回 true。

    <?php
       $pattern = "file?.txt";
       $string = "file1.txt";
    
       if (fnmatch($pattern, $string, FNM_PERIOD)) {
          echo "The string matches the pattern.";
       } else {
          echo "The string does not match the pattern.";
       }
    ?> 
    

    輸出

    這將產生以下結果:

    如果模式和字串匹配:

    The string matches the pattern
    

    如果模式和字串不匹配:

    The string does not match the pattern.
    

    示例

    在此程式碼中,我們將檢查檔名是否以 .jpg 結尾。由於 image.jpg 與模式匹配,它將列印成功訊息。

    <?php
       $file = "picture.jpg";
       if (fnmatch("*.jpg", $file)) {
          echo "This is a JPEG image.";
       } else {
          echo "This is not a JPEG image.";
       }
    ?> 
    

    輸出

    這將導致以下結果:

    This is a JPEG image.
    

    示例

    在此程式碼中,我們將檢查檔名是否以“index”開頭並以 .pdf 結尾。因此,如果檔案與模式匹配,它將列印成功訊息。

    <?php
       $file = "index2024.pdf";
       if (fnmatch("index*.pdf", $file)) {
          echo "This is an index file.";
       } else {
          echo "This is not an index file.";
       }
    ?> 
    

    輸出

    這將建立以下輸出:

    This is a index file.
    

    常見用例

    • 它可用於過濾檔案列表。
    • 用於將使用者輸入與預定義模式匹配。
    • 用於驗證檔名或副檔名。

    總結

    使用 PHP 的fnmatch()函式將檔名或字串與給定模式匹配。類似於 shell 命令,它主要用於識別複製萬用字元的模式。

    php_function_reference.htm
    廣告