php - 如何摆脱 .和 .. 在扫描文件夹时在 php 中创建一个数组?

标签 php regex arrays file directory

如果您扫描包含其他文件夹和文件的文件夹,您如何摆脱 .和..和文件?你如何把没有 .和 ..? 我想使用正则表达式,但我是新手,无法正确使用。 我的代码现在是这样的,但不起作用:

if(fnmatch("\.{1,2}",$dir_array[$i]) || is_file($dir_array[$i]){
unset($dir_array[$i]);
}else{ //other code
}

最佳答案

您在代码中混淆了 fnmatch 和正则表达式。要获取除特殊文件和目录之外的所有文件和目录,请使用:

$dir_array = array_diff($dir_array, array(".", ".."));

或者,如果您无论如何都要迭代数组,您可以像这样测试每个元素:

foreach ($dir_array as $name) {
    if (($name != "..") && ($name != ".")) {
        // Do stuff on all files and directories except . ..
        if (is_dir($name)) {
            // Do stuff on directories only
        }
    }
}

在 php<5.3 中,你可以独占 use a callback function ,也是:

$dir_array = array_filter($dir_array,
  create_function('$n', 'return $n != "." && $n != ".." && is_dir($n);'));

(请参阅 Allain Lalonde 的回答以获得更详细的版本)

从 php 5.3 开始,这可以写成 nicer :

$dir_array = array_filter($dir_array,
  function($n) {return $n != "." && $n != ".." && is_dir($n);});

最后,结合 array_filter 和这个答案的第一行代码会产生一个(微不足道的)慢,但可能更易读的版本:

$dir_array = array_filter(array_diff($dir_array, array(".", "..")), is_dir);

关于php - 如何摆脱 .和 .. 在扫描文件夹时在 php 中创建一个数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/533199/

相关文章:

php - 在网站上包含 google pub

php - 我可以从 doctrine2 中的 php 访问鉴别器字段吗?

javascript - 时间字符串到日期对象转换js angularJS

c++ - 尝试设置一个数组以将最后三笔存款存储到银行账户系统中

php - 在 Travis 上使用 php-imagick 阅读 pdf 文件

JavaScript 替换正则表达式

javascript - 正则表达式查找包含这些字母的单词

java - 手动代码计算

c# - 请求一个 linq 来操作数组的数组

php - 摆脱 mysql_real_escape_string() 解析字符串上的\字符