PHP 檔案系統 glob() 函式



PHP 檔案系統glob()函式可用於查詢與模式匹配的檔案和目錄。當您需要列出目錄中的檔案時,此方法非常有用。

語法

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

array glob(string $pattern, int $flags);

引數

以下是glob()函式的必需和可選引數:

序號 引數及描述
1

$pattern (必需)

要搜尋的模式。您可以使用萬用字元,例如:

  • * 匹配任意數量的字元。
  • ? 匹配恰好一個字元。
2

$flags (可選)

它可以用來控制搜尋的行為。

一些常見的標誌是:

  • GLOB_ONLYDIR: 只返回目錄。
  • GLOB_MARK: 為每個返回的目錄新增斜槓 (/)。
  • GLOB_NOSORT: 按發現順序返回檔案,不排序。
  • GLOB_NOCHECK: 如果未找到匹配項,則返回搜尋模式。

返回值

PHP 中的glob()函式返回一個包含匹配的目錄和檔案的陣列。如果未找到匹配項且未設定 GLOB_NOCHECK 標誌,則它將生成一個空陣列。如果發生錯誤,則返回 FALSE。

PHP 版本

glob()函式最初作為 PHP 4.3.0 的核心部分引入,並能與 PHP 5、PHP 7 和 PHP 8 良好地配合使用。

示例

我們使用了 PHP 檔案系統glob()函式來查詢當前目錄中的所有 .txt 檔案。此示例使用 '*' 萬用字元查詢當前目錄中所有副檔名為 .txt 的檔案。

<?php
   // Look for all the text files using glob function
   $txtFiles = glob("*.txt");

   // print array of the text files
   print_r($txtFiles);
?>

輸出

以下是以下程式碼的結果:

Array
(
    [0] => myfile.txt
    [1] => sample.txt
)

示例

此 PHP 示例使用 glob 函式查詢特定目錄中的所有 .jpg 檔案。因此我們在路徑之後使用了 *.jpg,其中 '*' 是萬用字元。因此它將獲取指定資料夾中存在的所有 .jpg 檔案。

<?php
   // get all the .jpg files in the specified folder
   $imageFiles = glob("/Users/abc/Desktop/PhpProjects/*.jpg");

   // print the .jpg file names 
   print_r($imageFiles);
?> 

輸出

這將產生以下結果:

Array
(
    [0] => /Users/abc/Desktop/PhpProjects/image.jpg
    [1] => /Users/abc/Desktop/PhpProjects/mypic.jpg
)

示例

在此 PHP 程式碼中,我們將使用glob()函式查詢當前目錄中的所有檔案和目錄,並使用 GLOB_ONLYDIR 可選引數為目錄新增尾隨斜槓。

<?php
   //  get all the directories in the current directory
   $directories = glob("*/", GLOB_ONLYDIR);

   //Print the directories 
   print_r($directories);
?> 

輸出

這將生成以下結果:

Array
(
    [0] => images/
    [1] => new dir/
)

示例

在此 PHP 程式碼中,我們將查詢當前目錄中的所有檔案和目錄,並使用 GLOB_MARK 引數為目錄新增尾隨斜槓。

<?php
   //  get all the files and directories in the current directory
   $items = glob("*", GLOB_MARK);
   
   //print the items here
   print_r($items);
?> 

輸出

這將產生以下輸出:

Array
(
    [0] => config.php
    [1] => csvfile.csv
    [2] => csvfile1.csv
    [3] => csvfile2.csv
    [4] => data.csv
    [5] => data1.csv
    [6] => error_log.log
    [7] => image.jpg
    [8] => images/
    [9] => index.php
    [10] => logo.gif
    [11] => myfile.txt
    [12] => myhtml.htm
    [13] => new dir/
    [14] => newfile.php
    [15] => sample.txt
)

注意

在某些平臺上,如果您使用 PHP 的glob()函式,則很難區分錯誤和空匹配。

總結

使用 PHP 的glob()函式,我們可以查詢與特定模式匹配的檔案和目錄。如果沒有匹配項(除非指定 GLOB_NOCHECK 標誌),它將建立一個空陣列;如果是這樣,它將返回 false。

php_function_reference.htm
廣告