使用正则表达式检查 PHP 中的文件扩展名

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/321158/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 22:23:14  来源:igfitidea点击:

Checking for file-extensions in PHP with Regular expressions

phpregex

提问by Vordreller

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

我正在读取单个目录中的所有文件,我想过滤 JPG、JPEG、GIF 和 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))\.)");

and the function takeFiles looks like this:

函数 takeFiles 看起来像这样:

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.

它总是不返回任何内容。所以我的正则表达式代码一定有问题。

回答by

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

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

I think this one might work for you:

我认为这个可能对你有用:

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

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

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

注意最后的 /i - 这是“不区分大小写”的标志,让您不必输入所有排列:)

回答by Eran Galperin

How about using glob()instead?

改用glob()怎么样?

$files = glob($dir . '*.{jpg,gif,png,jpeg}',GLOB_BRACE);

回答by smack0007

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

有什么理由不想使用scandirandpathinfo吗?

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.

因此,您还可以检查文件是否为目录并执行递归调用以扫描该目录。我匆忙编写了代码,所以可能不是 100% 正确。

回答by Rodrigo

This works out for me

这对我有用

$string = "your-file-name.jpg";
preg_match("/\b(\.jpg|\.JPG|\.png|\.PNG|\.gif|\.GIF)\b/", $string, $output_array);

Best.

最好的事物。

回答by angus

You should put slashes around your regexp. -> "/(...)/"

你应该在你的正则表达式周围加上斜线。-> "/(...)/"

回答by ringmaster

There are a few ways of doing this.

有几种方法可以做到这一点。

Have you tried glob()?:

你试过glob()吗?:

$files = glob("{$picsDir}/*.{gif,jpeg,jpg,png}", GLOB_BRACE);

Have you considered pathinfo()?:

你考虑过pathinfo()吗?:

$info = pathinfo($file);
switch(strtolower($info['extension'])) {
    case 'jpeg':
    case 'jpg':
    case 'gif':
    case 'png':
        $files[] = $file;
        break;
}

If you're insistant upon using the regular expression, there's no need to match the whole filename, just the extension. Use the $token to match the end of the string, and use the iflag to denote case-insensitivity. Also, don't forget to use a delimiter in your expression, in my case "%":

如果您坚持使用正则表达式,则无需匹配整个文件名,只需匹配扩展名。使用$标记来匹配字符串的结尾,并使用i标志来表示不区分大小写。另外,不要忘记在表达式中使用分隔符,在我的例子中是“%”:

$rex = '%\.(gif|jpe?g|png)$%i';

回答by zeros-and-ones

Here are two different ways to compile an array of files by type (conf for demo) from a target directory. I'm not sure which is better performance wise.

这里有两种不同的方法可以从目标目录中按类型(用于演示的 conf)编译文件数组。我不确定哪个更好的性能明智。

    $path    = '/etc/apache2/';
    $conf_files = []; 

    // Remove . and .. from the returned array from scandir
    $files = array_diff(scandir($path), array('.', '..'));
    foreach($files as $file) {
        if(in_array(pathinfo($file, PATHINFO_EXTENSION), ['conf'])) {
            $conf_files[] = $file;   
        }   
    }
    return $conf_files;

This will return the full file path not just the file name

这将返回完整的文件路径,而不仅仅是文件名

return $files = glob($path . '*.{conf}',GLOB_BRACE);