How do I get a file extension in PHP?

前端 未结 28 2254
一向
一向 2020-11-21 22:45

This is a question you can read everywhere on the web with various answers:

$ext = end(explode(\'.\', $filename));
$ext = substr(strrchr($filename, \'.\'), 1         


        
28条回答
  •  执笔经年
    2020-11-21 23:24

    Although the "best way" is debatable, I believe this is the best way for a few reasons:

    function getExt($path)
    {
        $basename = basename($path);
        return substr($basename, strlen(explode('.', $basename)[0]) + 1);
    }
    
    1. It works with multiple parts to an extension, eg tar.gz
    2. Short and efficient code
    3. It works with both a filename and a complete path

提交回复
热议问题