17

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 extension? Here's the code I've been working with but I'm hoping to get something more elegant. Is there an out of the box solution?

$file = new SplFileInfo("path/to/file.txt.zip"); 

echo 'basename: '.$file->getBasename();  
echo PHP_EOL;
echo 'filename: '.$file->getFilename();
echo PHP_EOL;    
echo 'extension: '.$file->getExtension();
echo PHP_EOL;    
echo 'basename w/o extension: '.$file->getBasename('.'.$file->getExtension());

>>OUTPUT
>>basename: file.txt.zip
>>filename: file.txt.zip
>>extension: zip
>>basename w/o extension: file.txt
tzvi
  • 471
  • 3
  • 5
  • 19

2 Answers2

30

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" 
Erenor Paz
  • 3,061
  • 4
  • 37
  • 44
-1

I couldnt find anything official like the .net's - Path.GetFileNameWithoutExtension https://msdn.microsoft.com/en-us/library/system.io.path.getfilenamewithoutextension%28v=vs.110%29.aspx

Here is what I'm using instead preg_replace("/.[^.]+$/", "", $file->getBasename());

I've tested it with "file.txt.zip" to make sure it returns "file.txt", not "file"

mrwaim
  • 1,841
  • 3
  • 20
  • 29
  • 11
    `$file->getBasename('.' . $file->getExtension())` is how this should be done, not a regex. – salathe May 28 '15 at 11:53
  • 1
    @salathe Submit this as an answer because this is the correct answer to this question. +1 – crmpicco Mar 02 '16 at 10:46
  • @crmpicco It was the best I could come up with too (read the OP carefully). I was hoping for something more direct and elegant. – tzvi Mar 02 '16 at 19:40