如何在PHP中获得文件扩展名? [英] How do I get a file extension in PHP?

查看:77
本文介绍了如何在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];

但是,总有最佳方法",它应该在堆栈溢出中.

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

推荐答案

来自其他脚本语言的人们总是认为它们更好,因为它们具有内置功能而不是PHP(我现在正在研究Pythonista: -)).

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.

享受

这篇关于如何在PHP中获得文件扩展名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆