如何在 PHP 中获得文件扩展名?

2022-01-30 00:00:00 file-extension php

这是一个您可以在网络上随处阅读的问题,并提供各种答案:

This is a question you can read everywhere on the web with various answers:

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

等等

然而,总有最好的方法",它应该在 Stack Overflow.

However, there is always "the best way" and it should be on Stack Overflow.

推荐答案

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

People from other scripting languages always think theirs is better because they have a built-in function to do that and not PHP (I am looking at Pythonistas right now :-)).

其实它确实存在,只是很少有人知道.认识pathinfo():

In fact, it does exist, but few people know it. Meet pathinfo():

$ext = pathinfo($filename, PATHINFO_EXTENSION);

这是快速且内置的.pathinfo() 可以为您提供其他信息,例如规范路径,具体取决于您传递给它的常量.

This is fast and built-in. pathinfo() can give you other information, such as canonical path, depending on the constant you pass to it.

请记住,如果您希望能够处理非 ASCII 字符,则需要先设置语言环境.例如:

Remember that if you want to be able to deal with non ASCII characters, you need to set the locale first. E.G:

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

另外,请注意,这不考虑文件内容或 mime 类型,您只会获得扩展名.但这是你要求的.

Also, note this doesn't take into consideration the file content or mime-type, you only get the extension. But it's what you asked for.

最后,请注意,这仅适用于文件路径,而不适用于使用 PARSE_URL 涵盖的 URL 资源路径.

Lastly, note that this works only for a file path, not a URL resources path, which is covered using PARSE_URL.

享受

相关文章