使用正则表达式检查PHP中的文件扩展名 [英] Checking for file-extensions in PHP with Regular expressions

查看:624
本文介绍了使用正则表达式检查PHP中的文件扩展名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在读取一个目录中的所有文件,并且想对JPG,JPEG,GIF和PNG进行过滤.

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.

我当前正在使用此

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

和功能takeFiles看起来像这样:

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.

推荐答案

我认为您的正则表达式有问题.首先尝试在此处测试正则表达式: https://www.regexpal.com/

I think something is wrong with your regex. Try testing regexes here first: https://www.regexpal.com/

我认为这可能对您有用:

I think this one might work for you:

/^.*\.(jpg|jpeg|png|gif)$/i

请注意最后的/i-这是不区分大小写"标志,省去了键入所有排列的麻烦:)

Note the /i at the end - this is the "case insensitive" flag, saves you having to type out all permutations :)

这篇关于使用正则表达式检查PHP中的文件扩展名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆