如何使用glob方法遍曆檔案夾下所有檔案的相關方法

來源:互聯網
上載者:User
遍曆檔案夾下所有檔案,一般可以使用opendir 與 readdir 方法來遍曆。

例子:找出指定目錄下的所有php檔案(不搜尋子檔案夾),代碼如下:

<?php$path = dirname(__FILE__);$result = traversing($path);print_r($result);function traversing($path){    $result = array();    if($handle = opendir($path)){        while($file=readdir($handle)){            if($file!='.' && $file!='..'){                if(strtolower(substr($file, -4))=='.php'){                    array_push($result, $file);                }            }        }    }    return $result;}?>

如使用glob方法來遍曆則可以簡化代碼

<?php$path = dirname(__FILE__);$result = glob($path.'/*.php');print_r($result);?>

注意,glob返回的會是path+搜尋結果的路徑,例如path=’/home/fdipzone’,以上例子則返回

Array(    [0] => /home/fdipzone/a.php    [1] => /home/fdipzone/b.php    [2] => /home/fdipzone/c.php)

這是與opendir,readdir返回的結果不同的地方。

如果只是遍曆目前的目錄。可以改成這樣:glob(‘*.php’);
glob文法說明:

array glob ( string $pattern [, int $flags = 0 ] )

glob() 函數依照 libc glob() 函數使用的規則尋找所有與 pattern 匹配的檔案路徑,類似於一般 shells 所用的規則一樣。不進行縮寫擴充或參數替代。glob使用正則匹配路徑功能強大。

flags 有效標記有:
GLOB_MARK - 在每個返回的項目中加一個斜線
GLOB_NOSORT - 按照檔案在目錄中出現的原始順序返回(不排序)
GLOB_NOCHECK - 如果沒有檔案匹配則返回用於搜尋的模式
GLOB_NOESCAPE - 反斜線不轉義元字元
GLOB_BRACE - 擴充 {a,b,c} 來匹配 ‘a’,’b’ 或 ‘c’
GLOB_ONLYDIR - 僅返回與模式比對的目錄項
GLOB_ERR - 停止並讀取錯誤資訊(比如說不可讀的目錄),預設的情況下忽略所有錯誤

例子:使用glob方法遍曆指定檔案夾(包括子檔案夾)下所有php檔案

<?php$path = dirname(__FILE__);$result = array();traversing($path, $result);print_r($result);function traversing($path, &$result){    $curr = glob($path.'/*');    if($curr){        foreach($curr as $f){            if(is_dir($f)){                array_push($result, $f);                traversing($f, $result);            }elseif(strtolower(substr($f, -4))=='.php'){                array_push($result, $f);            }        }    }}?>

本文講解了如何使用glob方法遍曆檔案夾下所有檔案的相關方法,更多相關內容請關注php中文網。

相關推薦:

關於php 浮點數比較方法 的講解

通過mysql匯出查詢結果到csv方法的講解

php array_push 與 $arr[]=$value 之間的效能對比

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.