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

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

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


当前回答

还有SplFileInfo:

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

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

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

其他回答

很抱歉“简短的问题;但不是简短的回答”

PATH示例1

$path = "/home/ali/public_html/wp-content/themes/chicken/css/base.min.css";
$name = pathinfo($path, PATHINFO_FILENAME);
$ext  = pathinfo($path, PATHINFO_EXTENSION);
printf('<hr> Name: %s <br> Extension: %s', $name, $ext);

URL示例2

$url = "//www.example.com/dir/file.bak.php?Something+is+wrong=hello";
$url = parse_url($url);
$name = pathinfo($url['path'], PATHINFO_FILENAME);
$ext  = pathinfo($url['path'], PATHINFO_EXTENSION);
printf('<hr> Name: %s <br> Extension: %s', $name, $ext);

示例1的输出:

Name: base.min
Extension: css

示例2的输出:

Name: file.bak
Extension: php

工具书类

https://www.php.net/manual/en/function.pathinfo.phphttps://www.php.net/manual/en/function.realpath.phphttps://www.php.net/manual/en/function.parse-url.php

我发现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()

在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

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

<?php

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

?>

谢谢

E-satis的响应是确定文件扩展名的正确方法。

或者,您可以使用fileinfo来确定文件的MIME类型,而不是依赖文件扩展名。

下面是处理用户上传的图像的简化示例:

// Code assumes necessary extensions are installed and a successful file upload has already occurred

// Create a FileInfo object
$finfo = new FileInfo(null, '/path/to/magic/file');

// Determine the MIME type of the uploaded file
switch ($finfo->file($_FILES['image']['tmp_name'], FILEINFO_MIME)) {        
    case 'image/jpg':
        $im = imagecreatefromjpeg($_FILES['image']['tmp_name']);
    break;

    case 'image/png':
        $im = imagecreatefrompng($_FILES['image']['tmp_name']);
    break;

    case 'image/gif':
        $im = imagecreatefromgif($_FILES['image']['tmp_name']);
    break;
}