How do I get a file extension in PHP?

前端 未结 28 2231
一向
一向 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:04

    There is also SplFileInfo:

    $file = new SplFileInfo($path);
    $ext  = $file->getExtension();
    

    Often you can write better code if you pass such an object around instead of a string. Your code is more speaking then. Since PHP 5.4 this is a one-liner:

    $ext  = (new SplFileInfo($path))->getExtension();
    

提交回复
热议问题