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

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

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


当前回答

路径信息()

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

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

其他回答

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

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

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

有时不使用pathinfo($path,pathinfo_EXTENSION)很有用。例如:

$path = '/path/to/file.tar.gz';

echo ltrim(strstr($path, '.'), '.'); // tar.gz
echo pathinfo($path, PATHINFO_EXTENSION); // gz

还要注意,pathinfo无法处理一些非ASCII字符(通常它只是从输出中抑制它们)。在扩展中,这通常不是一个问题,但了解这一警告也无妨。

事实上,我在找这个。

<?php

$url = 'http://example.com/myfolder/sympony.mp3?a=1&b=2#XYZ';
$tmp = @parse_url($url)['path'];
$ext = pathinfo($tmp, PATHINFO_EXTENSION);

var_dump($ext);

快速修复可能是这样的。

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