【问题标题】:excluding certain files based on filename根据文件名排除某些文件
【发布时间】:2014-07-28 06:31:14
【问题描述】:

所以我有一个代码 sn-p 读取目录并对里面的文件执行某些操作。我有一组要排除的文件名。我的代码如下所示:

$excluded = array(".","..","thumbs.db");

if($fh = @opendir($dir)) 
{
    while(false !== ($file = @readdir($fh))) 
    {
       if(in_array(strtolower($file),$excluded))
       {
          continue;
       }
       //do processing here...

现在,我希望 zip 文件也应该被排除在外。由于我不知道它们可能存在于什么名称中,因此我需要根据扩展名跳过它们。

现在我知道我可以拆分文件名并查看最后一个元素以查看它是否压缩等,但我想问的是,有没有办法在已经编码的约束范围内实现它 - 比如添加就像这样,然后调整循环来处理它......

 $excluded = array(".","..","thumbs.db","*.zip");

【问题讨论】:

标签: php file directory


【解决方案1】:

这应该可以解决问题:

$excluded = array(".","..","thumbs.db");
$excludedExtensions = array(".zip",".rar");

if($fh = @opendir($dir)) 
{
    while(false !== ($file = @readdir($fh))) 
    {
       if(in_array(strtolower($file),$excluded) || 
          in_array(strtolower(substr($file, -4)), $excludedExtensions) )
       {
          continue;
       }
       //do processing here...

这不是你要找的东西,但我认为不可能按照你想要的方式去做:(

------------------------------------------ ------------------------------------------

编辑

我想用一种更可靠的方法来做到这一点,因为有些文件的扩展名中有 4 个甚至 5 个字母。在查看 PHP 手册后,我发现了这个:

$excluded = array(".","..","thumbs.db");
$excludedExtensions = array(".zip",".rar", ".7z", ".jpeg", ".phtml");

if($fh = @opendir($dir)) 
{
    while(false !== ($file = @readdir($fh))) 
    {
       $path_parts = pathinfo($file);

       if(in_array(strtolower($file),$excluded) ||
          in_array(strtolower($path_parts['extension'])) )
       {
          continue;
       }
       //do processing here...

在此处查看更多信息:PHP manual: pathinfo

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-19
    • 1970-01-01
    • 2015-07-01
    • 1970-01-01
    • 2021-01-23
    相关资源
    最近更新 更多