北城已荒凉 2008-10-06 11:00 采纳率: 0%
浏览 767
已采纳

如何在 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条)

报告相同问题?

悬赏问题

  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮