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

$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示例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

其他回答

还有SplFileInfo:

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

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

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

只要它不包含路径,您也可以使用:

array_pop(explode('.', $fname))

其中$fname是文件的名称,例如:my_picture.jpg。结果将是:jpg

事实上,我在找这个。

<?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);

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;
}

来自其他脚本语言的人总是认为他们的脚本更好,因为他们有一个内置函数来实现这一点,而不是PHP(我现在正在看Pythonista:-))。

事实上,它确实存在,但很少有人知道它

$ext = pathinfo($filename, PATHINFO_EXTENSION);

这是快速和内置的。pathinfo()可以根据传递给它的常量提供其他信息,例如规范路径。

请记住,如果您希望能够处理非ASCII字符,则需要首先设置区域设置。例如:

setlocale(LC_ALL,'en_US.UTF-8');

此外,请注意,这没有考虑文件内容或mime类型,您只获得扩展名。但这是你要求的。

最后,请注意,这只适用于文件路径,而不是URL资源路径,这是使用PARSE_URL覆盖的。

享受