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

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

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


当前回答

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

这会奏效的

$ext = pathinfo($filename, PATHINFO_EXTENSION);

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

<?php

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

?>

谢谢

您也可以尝试一下(它适用于PHP5.*和7):

$info = new SplFileInfo('test.zip');
echo $info->getExtension(); // ----- Output -----> zip

提示:如果文件没有扩展名,则返回空字符串

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

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

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

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