Home > Article > Backend Development > How to remove file extension in php
php method to remove the file extension: 1. Use the pathinfo function to return part of the complete file name; 2. Use the basename function to remove the extension from the file name; 3. Use the substr and strrpos functions to return no extension The full path and filename of the name.
Recommended: "PHP Video Tutorial"
PHP removes the extension from the file name (filename) Three Ways to Name (Extension)
If you have a file name and you need to remove the extension (extension) from PHP, there are many ways to do this. There are three methods here.
Use the pathinfo() function
The pathinfo() function returns an array containing dirname, basename, extension and filename. Alternatively, you can pass a PATHINFO_ constant and return that portion of the full filename:
$filename ='filename.html'; $without_extension = pathinfo($filename, PATHINFO_FILENAME);
If the filename contains a full path, only the filename without the extension is returned.
Using the basename() function
If the extension is known and is the same for all filenames, the second optional argument can be passed to basename() to tell it to remove that extension from the filename:
$filename ='filename.html'; $without_extension = basename($filename,'.html');
If the filename contains a full path, 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, return the full path and filename without extension. You can use basename() to remove the path, for example:
basename(substr($filename, 0, strrpos($filename, ".")));
although it is slower than using pathinfo.
Speed comparison
Run each of these in a loop 10,000,000 times on Mac using PHP 5.4:
pathinfo:10.13秒 basename:7.87秒 substr / strrpos:6.05秒 basename(substr / strrpos):11.98秒
If the filename does not contain the full path , or if it's not important, the substr/strrpos options seem to be the fastest.
If the filename contains a path and you don't want the path but do know what extension you want to remove, basename seems to be fastest.
If the file name contains a path, the path is not required and the extension is not known, then use the pathinfo() option.
Conclusion
There are many other ways to do this, some may be faster. In many cases, speed may not be that important (10 seconds to run pathinfo is 100,000 times after all). The purpose of this article is to show some ways to remove extensions from file names using PHP.
The above is the detailed content of How to remove file extension in php. For more information, please follow other related articles on the PHP Chinese website!