How do I get a file extension in PHP?(如何在 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.
享受
这篇关于如何在 PHP 中获得文件扩展名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在 PHP 中获得文件扩展名?
基础教程推荐
- 在多维数组中查找最大值 2021-01-01
- 通过 PHP SoapClient 请求发送原始 XML 2021-01-01
- WooCommerce 中选定产品类别的自定义产品价格后缀 2021-01-01
- Libpuzzle 索引数百万张图片? 2022-01-01
- 如何在 PHP 中的请求之间持久化对象 2022-01-01
- 超薄框架REST服务两次获得输出 2022-01-01
- XAMPP 服务器不加载 CSS 文件 2022-01-01
- 在 PHP 中强制下载文件 - 在 Joomla 框架内 2022-01-01
- mysqli_insert_id 是否有可能在高流量应用程序中返回 2021-01-01
- 在 Woocommerce 中根据运输方式和付款方式添加费用 2021-01-01