叼花硬汉 2008-10-06 11:00 采纳率: 0%
浏览 729
已采纳

如何在 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条回答 默认 最新

  • 7*4 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条)

报告相同问题?