Tuesday, 18 September 2018

Remove extension from a filename with PHP

If you've got a filename that you need to remove the extension from with PHP, there are a number of ways to do it. Here's three ways, with some benchmarking.

Using pathinfo

The pathinfo() function returns an array containing the directory name, basename, extension and filename. Alternatively, you can pass it one of the PATHINFO_ constants and just return that part of the full filename:
$filename = 'filename.html';
$without_extension = pathinfo($filename, PATHINFO_FILENAME);
If the filename contains a full path, then only the filename without the extension is returned.

Using basename

If the extension is known and is the same for the all the filenames, you can pass the second optional parameter to basename() to tell it to strip that extension from the filename:
$filename = 'filename.html';
$without_extension = basename($filename, '.html');
If the filename contains a full path, then only the filename without the extension is returned.

Using substr and strrpos

$filename = 'filename.html';
$without_extension = substr($filename, 0, strrpos($filename, "."));
If the filename contains a full path, then the full path and filename without the extension is returned. You could basename() it as well to get rid of the path if needed (e.g. basename(substr($filename, 0, strrpos($filename, ".")))) although it's slower than using pathinfo.

Benchmarking

Running each of these in a loop 10,000,000 times on my Mac with PHP 5.4:
pathinfo: 10.13 seconds
basename: 7.87 seconds
substr/strrpos: 6.05 seconds
basename(substr/strrpos): 11.98 seconds
If the filename doesn't contain the full path or it doesn't matter if it does, then the substr/strrpos option appears to be the fastest.
If the filename does contain a path and you don't want the path but do know what the extension you want to remove is, then basename appears to be the fastest.
If the filename contains a path, you don't want the path and you don't know what the extension is, then use the pathinfo() option.

Conclusion

There will be plenty of other ways to do this, and some may be faster. In a lot of cases, the speed probably doesn't really matter that much (the 10 seconds to run pathinfo was 10 million times, after all); the purpose of this post was to show a few ways to remove the extension from the filename with PHP.

Related posts:

0 comments:

Post a Comment