如何摆脱 . 和..在扫描文件夹时在 php 中创建数组?
如果您扫描包含其他文件夹和文件的文件夹,如何删除 . 和..和文件? 如何放入仅数组的文件夹而无需 . 和 ..? 我想使用正则表达式,但我是新手,我无法正确使用。 我的代码现在是这样的,但不起作用:
if(fnmatch("\.{1,2}",$dir_array[$i]) || is_file($dir_array[$i]){
取消设置($dir_array[$i]);
}别的{ //其他代码
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
您在代码中混淆了 fnmatch 和正则表达式。 要获取除特殊文件和目录之外的所有文件和目录,请使用以下命令:
或者,如果您无论如何都迭代数组,则可以像这样测试每个元素:
在 php<5.3 中,您可以专门使用 也使用回调函数:(
有关更详细的版本,请参阅 Allin Lalonde 的答案)
从 php 5.3 开始,这可以是写成 更好:
最后,将 array_filter 和这个答案的第一行代码结合起来会产生一个(微不足道的) )较慢,但可能更具可读性的版本:
You are confusing fnmatch and regular expressions in your code. To get all files and directories except the special ones, use this:
Alternatively, if you iterate the array anyway, you can test each element like this:
In php<5.3, you can exclusively use a callback function, too:
(See Allain Lalonde's answer for a more verbose version)
Since php 5.3, this can be written nicer:
Finally, combining array_filter and the first line of code of this answer yields an (insignificantly) slower, but probably more readable version:
您不需要正则表达式来测试它。 只需使用纯字符串比较:
You don’t need a regular expression to test this. Just use plain string comparison:
不需要正则表达式,只需 unset() 前两个值。
no regex is needed, just unset() the first two values.
这个可以做到。
This may do it.
我会这样做:
虽然,我更喜欢 DirectoryFilterDots 但这在可用的 PHP 发行版中很少见。
I would do it like this:
Although, I'd rather prefer DirectoryFilterDots but it's kind of rare in the available PHP distributions.
我会做这样的事情(代码可能无法毫不费力地工作,因为我已经多年没有使用 PHP 了)
编辑误读了问题 - 现在应该将所有文件夹名称 ion myPath 添加到数组中那些不是“。” 或者 ”..”
I'd do something like this (code may not work without effort since I haven't worked in PHP for years)
EDIT misread the question - This should now add to the array all the folder names ion myPath that are not "." or ".."