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 are three ways.
pathinfo()
The pathinfo()
the 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= pathinfo('filename.php', PATHINFO_FILENAME);
If the filename contains a full path, then only the filename without the extension is returned. If the filename contains a path, you don’t want the path and you don’t know what the extension is, the pathinfo()
option is the best.
basename()
If the extension is known and is the same for all the filenames, you can pass the second optional parameter to basename()
to tell it to strip that extension from the filename:
$filename = basename('filename.php', '.png');
If the filename contains a full path, then only the filename without the extension is returned. 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.
substr() and strrpos()
$filename = 'filename.php'; $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()
. 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.
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 purpose of this post was to show a few ways to remove the extension from the filename with PHP.