本文共 1261 字,大约阅读时间需要 4 分钟。
获取目录中带有过滤器 (第二个参数)的所有文件和文件夹,如果使用.或,请勿调用函数..。
您的代码:
function getDirContents($dir, $filter = '', &$results = array()) {
$files = scandir($dir);
foreach($files as $key => $value){
$path = realpath($dir.DIRECTORY_SEPARATOR.$value);
if(!is_dir($path)) {
if(empty($filter) || preg_match($filter, $path)) $results[] = $path;
} elseif($value != "." && $value != "..") {
getDirContents($path, $filter, $results);
}
}
return $results;
}
// Simple Call: List all files
var_dump(getDirContents('/xampp/htdocs/WORK'));
// Regex Call: List php files only
var_dump(getDirContents('/xampp/htdocs/WORK', '/\.php$/'));
输出(示例):
// Simple Call
array(13) {
[0]=> string(69) "/xampp/htdocs/WORK.htaccess"
[1]=> string(73) "/xampp/htdocs/WORKConverter.php"
[2]=> string(69) "/xampp/htdocs/WORKEvent.php"
[3]=> string(70) "/xampp/htdocs/WORKdefault_filter.json"
[4]=> string(68) "/xampp/htdocs/WORKdefault_filter.xml"
[5]=> string(80) "/xampp/htdocs/WORKCaching/ApcCache.php"
[6]=> string(84) "/xampp/htdocs/WORKCaching/CacheFactory.php"
}
// Regex Call
array(13) {
[0]=> string(69) "/xampp/htdocs/WORKEvent.php"
[1]=> string(73) "/xampp/htdocs/WORKConverter.php"
[2]=> string(80) "/xampp/htdocs/WORKCaching/ApcCache.php"
[3]=> string(84) "/xampp/htdocs/WORKCaching/CacheFactory.php"
}
转载地址:http://beqhp.baihongyu.com/