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

$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

其他回答

路径信息()

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

echo $path_info['extension']; // "bill"
ltrim(strstr($file_url, '.'), '.')

如果文件名像name.name.name.ext(丑陋,但有时会发生这种情况

我发现pathinfo()和SplFileInfo解决方案对于本地文件系统上的标准文件很好,但如果您使用远程文件,可能会遇到困难,因为有效图像的URL可能有#(片段标识符)和/或?(查询参数),这两个解决方案都将(不正确)作为文件扩展名的一部分。

我发现这是一种在URL上使用pathinfo()的可靠方法,首先对其进行解析以去除文件扩展名后不必要的混乱:

$url_components = parse_url($url); // First parse the URL
$url_path = $url_components['path']; // Then get the path component
$ext = pathinfo($url_path, PATHINFO_EXTENSION); // Then use pathinfo()

快速修复可能是这样的。

// 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
    $files = glob("abc/*.*"); // abc is the folder all files inside folder
    //print_r($files);
    //echo count($files);
    for($i=0; $i<count($files); $i++):
         $extension = pathinfo($files[$i], PATHINFO_EXTENSION);
         $ext[] = $extension;
         // Do operation for particular extension type
         if($extension=='html'){
             // Do operation
         }
    endfor;
    print_r($ext);
?>