Checking for file-extensions in PHP with Regular e

2020-02-23 08:20发布

I'm reading all the files in a single directory and I want to filter on JPG,JPEG,GIF and PNG.

Both capital and small letters. Those are the only files to be accepted.

I am currently using this:

$testPics = takeFiles($picsDir, "([^\s]+(?=\.(jpg|JPG|jpeg|JPEG|png|PNG|gif|GIF))\.\2)");

and the function takeFiles looks like this:

function takerFiles($dir, $rex="") {
    $dir .= "/";
    $files = array();
    $dp = opendir($dir);
    while ($file = readdir($dp)) {
      if ($file == '.')  continue;
      if ($file == '..') continue;
      if (is_dir($file)) continue;
      if ($rex!="" && !preg_match($rex, $file)) continue;
      $files[] = $file;
    }
    closedir($dp);
    return $files;
  }

And it always returns nothing. So something must be wrong with my regex code.

标签: php regex
7条回答
祖国的老花朵
2楼-- · 2020-02-23 08:51

Is there any reason you don't want to use scandir and pathinfo?

public function scanForFiles($path, array $exts)
{
    $files = scanDir($path);

    $return = array();

    foreach($files as $file)
    {
        if($file != '.' && $file != '..')
        {
            if(in_array(pathinfo($file, PATHINFO_EXTENSION), $exts))) {
                $return[] = $file;   
            }
        }
    }

    return $return;
}

So you could also check if the file is a directory and do a recursive call to scan that directory. I wrote the code in haste so might not be 100% correct.

查看更多
登录 后发表回答