这是一个问题,你可以在网络上的任何地方看到各种答案:

$ext = end(explode('.', $filename));
$ext = substr(strrchr($filename, '.'), 1);
$ext = substr($filename, strrpos($filename, '.') + 1);
$ext = preg_replace('/^.*\.([^.]+)$/D', '$1', $filename);

$exts = split("[/\\.]", $filename);
$n    = count($exts)-1;
$ext  = $exts[$n];

etc.

然而,总是有“最好的方法”,它应该是堆栈溢出。


当前回答

Use

str_replace('.', '', strrchr($file_name, '.'))

以便快速检索扩展名(如果您确定文件名有扩展名)。

其他回答

$ext=preg_replace('/^.*\.([^.]+)$/D','$1',$fileName);

pregreplace方法我们使用正则表达式搜索和替换。在preg_replace函数中,第一个参数是搜索的模式,第二个参数$1是对第一个(.*)匹配的对象的引用,第三个参数是文件名。

另一种方法是,我们还可以使用strrpos来查找“”的最后一次出现的位置并将该位置递增1,使其从(.)开始分解字符串

$ext=substr($fileName,strrpos($fileName,'.')+1);

快速修复可能是这样的。

// Exploding the file based on the . operator
$file_ext = explode('.', $filename);

// Count taken (if more than one . exist; files like abc.fff.2013.pdf
$file_ext_count = count($file_ext);

// Minus 1 to make the offset correct
$cnt = $file_ext_count - 1;

// The variable will have a value pdf as per the sample file name mentioned above.
$file_extension = $file_ext[$cnt];

只要它不包含路径,您也可以使用:

array_pop(explode('.', $fname))

其中$fname是文件的名称,例如:my_picture.jpg。结果将是:jpg

IMO,如果你有像name.name.name.ext这样的文件名(很难看,但有时会发生这种情况),这是最好的方法:

$ext     = explode('.', $filename); // Explode the string
$my_ext  = end($ext); // Get the last entry of the array

echo $my_ext;

E-satis的响应是确定文件扩展名的正确方法。

或者,您可以使用fileinfo来确定文件的MIME类型,而不是依赖文件扩展名。

下面是处理用户上传的图像的简化示例:

// Code assumes necessary extensions are installed and a successful file upload has already occurred

// Create a FileInfo object
$finfo = new FileInfo(null, '/path/to/magic/file');

// Determine the MIME type of the uploaded file
switch ($finfo->file($_FILES['image']['tmp_name'], FILEINFO_MIME)) {        
    case 'image/jpg':
        $im = imagecreatefromjpeg($_FILES['image']['tmp_name']);
    break;

    case 'image/png':
        $im = imagecreatefrompng($_FILES['image']['tmp_name']);
    break;

    case 'image/gif':
        $im = imagecreatefromgif($_FILES['image']['tmp_name']);
    break;
}