简体   繁体   English

根据文件名排除某些文件

[英]excluding certain files based on filename

So I have a code snippet that reads a directory and performs certain actions on the files inside. 因此,我有一个代码片段,可以读取目录并对其中的文件执行某些操作。 I have an array of filenames to exclude. 我要排除的文件名数组。 My code looks like this: 我的代码如下所示:

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

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

Now, I want it that zip files also should be excluded. 现在,我希望也应排除zip文件。 Since I do not know what name they might exist in, I will need to skip them based on extension. 由于我不知道它们可能存在的名字,因此我需要根据扩展名跳过它们。

Now I know I can split the filename and look at the last element to see if it zip etc, but what I wanted to ask is, is there a way to achieve it within the constraints of what is coded already - like adding it like this, and then tweaking the loop to handle it... 现在我知道我可以拆分文件名并查看最后一个元素以查看它是否压缩等,但是我想问的是,有没有一种方法可以在已经编码的限制内实现它-像这样添加它,然后调整循环以进行处理...

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

This should do the trick: 这应该可以解决问题:

$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...

It's not exactly what you're looking for, but i don't think it's possible to do the way you wanted it to :( 这并不是您要找的东西,但是我认为您不可能按照您想要的方式来做:(

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

EDIT 编辑

I wanted to make a more reliable way to do this, since there is some files which have 4 or even 5 letters in their extension. 我想提供一种更可靠的方法来执行此操作,因为有些文件的扩展名带有4个或什至5个字母。 After looking though the PHP manual, i found this: 在查看了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...

See more here: PHP manual: pathinfo 在此处查看更多信息: PHP手册:pathinfo

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM