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

$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.

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


当前回答

在PHP中获取文件扩展名的最简单方法是使用PHP的内置函数pathinfo。

$file_ext = pathinfo('your_file_name_here', PATHINFO_EXTENSION);
echo ($file_ext); // The output should be the extension of the file e.g., png, gif, or html

其他回答

1) 如果您正在使用(PHP 5>=5.3.6)可以使用SplFileInfo::getExtension-获取文件扩展名

示例代码

<?php

$info = new SplFileInfo('test.png');
var_dump($info->getExtension());

$info = new SplFileInfo('test.tar.gz');
var_dump($info->getExtension());

?>

这将输出

string(3) "png"
string(2) "gz"

2) 如果您正在使用(PHP4>=4.0.3,PHP5),另一种获取扩展名的方法是pathinfo

示例代码

<?php

$ext = pathinfo('test.png', PATHINFO_EXTENSION);
var_dump($ext);

$ext = pathinfo('test.tar.gz', PATHINFO_EXTENSION);
var_dump($ext);

?>

这将输出

string(3) "png"
string(2) "gz"

//EDIT:删除支架

您也可以尝试以下操作:

 pathinfo(basename($_FILES["fileToUpload"]["name"]), PATHINFO_EXTENSION)

我尝试了一个简单的解决方案,它可能会帮助其他人从具有get参数的URL中获取文件名

<?php

$path = "URL will be here";
echo basename(parse_url($path)['path']);

?>

谢谢

快速修复可能是这样的。

// 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];

路径信息()

$path_info = pathinfo('/foo/bar/baz.bill');

echo $path_info['extension']; // "bill"