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

发布于 2024-07-13 20:32:29 字数 298 浏览 5 评论 0 原文

如果您扫描包含其他文件夹和文件的文件夹,如何删除 . 和..和文件? 如何放入仅数组的文件夹而无需 . 和 ..? 我想使用正则表达式,但我是新手,我无法正确使用。 我的代码现在是这样的,但不起作用:

if(fnmatch("\.{1,2}",$dir_array[$i]) || is_file($dir_array[$i]){
取消设置($dir_array[$i]);
}别的{ //其他代码
}

If you scan a folder containing other folders AND files, how do you get rid of . and .. and files? How do you put in array only folders WITHOUT . and ..?
I would like to use regular expression, but I'm newbie and I can't get it right.
My code is now this but doesn't work:

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

终难遇 2024-07-20 20:32:29

您在代码中混淆了 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 中,您可以专门使用 也使用回调函数:(

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

有关更详细的版本,请参阅 Allin Lalonde 的答案)

从 php 5.3 开始,这可以是写成 更好

$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);

You are confusing fnmatch and regular expressions in your code. To get all files and directories except the special ones, use this:

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

Alternatively, if you iterate the array anyway, you can test each element like this:

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
        }
    }
}

In php<5.3, you can exclusively use a callback function, too:

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

(See Allain Lalonde's answer for a more verbose version)

Since php 5.3, this can be written nicer:

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

Finally, combining array_filter and the first line of code of this answer yields an (insignificantly) slower, but probably more readable version:

$dir_array = array_filter(array_diff($dir_array, array(".", "..")), is_dir);
倒数 2024-07-20 20:32:29

您不需要正则表达式来测试它。 只需使用纯字符串比较:

if ($dir_array[$i] == '.' || $dir_array[$i] == '..' || is_file($dir_array[$i])) {
    unset($dir_array[$i]);
}

You don’t need a regular expression to test this. Just use plain string comparison:

if ($dir_array[$i] == '.' || $dir_array[$i] == '..' || is_file($dir_array[$i])) {
    unset($dir_array[$i]);
}
書生途 2024-07-20 20:32:29

不需要正则表达式,只需 unset() 前两个值。

$d = dir($dir);
unset($d[0]);
unset($d[1]);

no regex is needed, just unset() the first two values.

$d = dir($dir);
unset($d[0]);
unset($d[1]);
久隐师 2024-07-20 20:32:29

这个可以做到。

function is_not_meta_dir($file_name) {
  // return true if $filename matches some pattern.
  // without knowing the format of your $dir_array
  return $file_name != '.' && $file_name != '..';
}

$new_dir_array = array_filter($dir_array, 'is_not_meta_dir');

This may do it.

function is_not_meta_dir($file_name) {
  // return true if $filename matches some pattern.
  // without knowing the format of your $dir_array
  return $file_name != '.' && $file_name != '..';
}

$new_dir_array = array_filter($dir_array, 'is_not_meta_dir');
失退 2024-07-20 20:32:29

我会这样做:

$items = array();
$handle = opendir('path/to/dir');
while (($item = readdir($handle)) !== false) {
    if (! in_array($item, array('.', '..'))) {
        $items[] = $item;
    }
}
closedir($handle);

print_r($items);

虽然,我更喜欢 DirectoryFilterDots 但这在可用的 PHP 发行版中很少见。

I would do it like this:

$items = array();
$handle = opendir('path/to/dir');
while (($item = readdir($handle)) !== false) {
    if (! in_array($item, array('.', '..'))) {
        $items[] = $item;
    }
}
closedir($handle);

print_r($items);

Although, I'd rather prefer DirectoryFilterDots but it's kind of rare in the available PHP distributions.

逐鹿 2024-07-20 20:32:29

我会做这样的事情(代码可能无法毫不费力地工作,因为我已经多年没有使用 PHP 了)

<?
if ($handle = opendir('/myPath')) 
  {
  while (false !== ($file = readdir($handle)))
  { 
    if (bool is_dir ( $file ) && substring($file,0,1) != ".")
      {
        $filesArray[] = $file; // this is the bit I'm not sure of the syntax for. 
      }
    }
  }
?>

编辑误读了问题 - 现在应该将所有文件夹名称 ion myPath 添加到数组中那些不是“。” 或者 ”..”

I'd do something like this (code may not work without effort since I haven't worked in PHP for years)

<?
if ($handle = opendir('/myPath')) 
  {
  while (false !== ($file = readdir($handle)))
  { 
    if (bool is_dir ( $file ) && substring($file,0,1) != ".")
      {
        $filesArray[] = $file; // this is the bit I'm not sure of the syntax for. 
      }
    }
  }
?>

EDIT misread the question - This should now add to the array all the folder names ion myPath that are not "." or ".."

烟酉 2024-07-20 20:32:29
        $pathsArr = array();
    foreach (explode($dirSeparator, $currentPath) as $path) {
        if (strlen($path) && $path !== '.') {
            if ($path === '..') {
                // die('.....');
                array_pop($pathsArr);
            } else {
                $pathsArr[] = $path;
            }
        }
    }

    $realpath = $winDrive . $dirSeparator . implode($dirSeparator, $pathsArr);
        $pathsArr = array();
    foreach (explode($dirSeparator, $currentPath) as $path) {
        if (strlen($path) && $path !== '.') {
            if ($path === '..') {
                // die('.....');
                array_pop($pathsArr);
            } else {
                $pathsArr[] = $path;
            }
        }
    }

    $realpath = $winDrive . $dirSeparator . implode($dirSeparator, $pathsArr);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文