SPLFileInfo: get filename without extension

后端 未结 2 2144
悲哀的现实
悲哀的现实 2021-02-13 07:23

I\'m accessing a number of files in the SPLFileInfo object. I see a way to get the path, filename, and even extension of the file. Is there a way to get the filename without ext

2条回答
  •  借酒劲吻你
    2021-02-13 07:32

    I'm late and all the credits should go to @salathe being the first helping the OP, but here's the link to PHP manual for basename function. Basically, you get the extension, then prepend a dot . and finally use the basename function to get the name, like this:

    $file->getBasename('.' . $file->getExtension())
    

    For fast reading, here's the PHP manual page's example:

    $info = new SplFileInfo('file.txt');
    var_dump($info->getBasename());
    
    $info = new SplFileInfo('/path/to/file.txt');
    var_dump($info->getBasename());
    
    $info = new SplFileInfo('/path/to/file.txt');
    var_dump($info->getBasename('.txt'));
    

    Output:

    string(8) "file.txt"
    string(8) "file.txt"
    string(4) "file" 
    

提交回复
热议问题