How do I get a file extension in PHP?

前端 未结 28 2328
一向
一向 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条回答
  •  旧时难觅i
    2020-11-21 23:21

    1) If you are using (PHP 5 >= 5.3.6) you can use SplFileInfo::getExtension — Gets the file extension

    Example code

    getExtension());
    
    $info = new SplFileInfo('test.tar.gz');
    var_dump($info->getExtension());
    
    ?>
    

    This will output

    string(3) "png"
    string(2) "gz"
    

    2) Another way of getting the extension if you are using (PHP 4 >= 4.0.3, PHP 5) is pathinfo

    Example code

    
    

    This will output

    string(3) "png"
    string(2) "gz"
    

    // EDIT: removed a bracket

提交回复
热议问题