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

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

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


当前回答

使用substr($path、strrpos($path,“.”)+1);。这是所有比较中最快的方法。

@库尔特·钟已经回答了。

让我们在这里查看比较结果:https://eval.in/661574

其他回答

快速修复可能是这样的。

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

在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
substr($path, strrpos($path, '.') + 1);

还有SplFileInfo:

$file = new SplFileInfo($path);
$ext  = $file->getExtension();

如果传递这样的对象而不是字符串,通常可以编写更好的代码。那么你的代码更能说话了。由于PHP 5.4,这是一行代码:

$ext  = (new SplFileInfo($path))->getExtension();

尽管“最佳方式”值得商榷,但我认为这是最佳方式,原因如下:

function getExt($path)
{
    $basename = basename($path);
    return substr($basename, strlen(explode('.', $basename)[0]) + 1);
}

它可以与扩展的多个部分一起工作,例如tar.gz简短高效的代码它可以使用文件名和完整路径