Checking for file-extensions in PHP with Regular expressions

前端 未结 7 2129
伪装坚强ぢ
伪装坚强ぢ 2020-12-28 17:30

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 accepte

7条回答
  •  臣服心动
    2020-12-28 17:57

    There are a few ways of doing this.

    Have you tried glob()?:

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

    Have you considered 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 i flag to denote case-insensitivity. Also, don't forget to use a delimiter in your expression, in my case "%":

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

提交回复
热议问题