How to remove an extension from a filename in PHP
Today, we’ll explain to you how to remove an extension from a filename in PHP.
If you want to get the filename then we can remove the extension from a filename and return only the filename using PHP. Here, we show you different ways to remove the extension from the filename and get only the filename in PHP.
Checkout more articles on PHP
Different ways to remove an extension from a filename in PHP
- Using pathinfo() function
- Using basename() function
- Using substr() and strrpos() functions
- Using regular expression
1. Using pathinfo() function
The pathinfo()
inbuilt PHP function returns an array containing the directory name
, basename
, extension
and filename
. To get only the filename, we can use PATHINFO_FILENAME
as shown below.
1 2 3 4 5 6 7 | <?php $filename = 'myfilename.php'; $without_ext = pathinfo($filename, PATHINFO_FILENAME); echo $without_ext; ?> // Output: myfilename |
2. Using basename() function
The basename()
inbuilt function is used when you know the extension of the file and pass it to the basename function to remove the extension from the filename.
1 2 3 4 5 6 7 | <?php $filename = 'myfilename.php'; $without_ext = basename($filename, '.php'); echo $without_ext; ?> // Output: myfilename |
3. Using substr() and strrpos() functions
We can also remove the file extension using substr()
and strrpos()
functions. The substr()
function returns the part of the string whereas strrpos()
finds the position of the last occurrence of substring in a string.
1 2 3 4 5 6 7 | <?php $filename = 'myfilename.php'; $without_ext = substr($filename, 0, strrpos($filename, ".")); echo $without_ext; ?> // Output: myfilename |
4. Using regular expression
Also, we can use the regular expression to get a filename without extension.
1 2 3 4 5 6 7 | <?php $filename = 'myfilename.php'; $without_ext = preg_replace('/.[^.]*$/', '', $filename); echo $without_ext; ?> // Output: myfilename |
I hope you find this article helpful.
Thank you for reading. Happy Coding..!! 🙂