必承其重 | 欲带皇冠 2008-10-06 11:00 采纳率: 0%
浏览 622
已采纳

如何在 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];

etc.

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

转载于:https://stackoverflow.com/questions/173868/how-to-getextract-a-file-extension-in-php

  • 写回答

21条回答 默认 最新

  • 游.程 2008-10-06 11:03
    关注

    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 :-)).

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

    $ext = pathinfo($filename, PATHINFO_EXTENSION);
    

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

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

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

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

    Enjoy

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(20条)

报告相同问题?

悬赏问题

  • ¥15 GD32 SPI通信时我从机原样返回收到的数据怎么弄?
  • ¥15 phython读取excel表格报错 ^7个 SyntaxError: invalid syntax 语句报错
  • ¥20 @microsoft/fetch-event-source 流式响应问题
  • ¥15 ogg dd trandata 报错
  • ¥15 高缺失率数据如何选择填充方式
  • ¥50 potsgresql15备份问题
  • ¥15 Mac系统vs code使用phpstudy如何配置debug来调试php
  • ¥15 目前主流的音乐软件,像网易云音乐,QQ音乐他们的前端和后台部分是用的什么技术实现的?求解!
  • ¥60 pb数据库修改与连接
  • ¥15 spss统计中二分类变量和有序变量的相关性分析可以用kendall相关分析吗?