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.

Different ways to remove an extension from a filename in PHP

  1. Using pathinfo() function
  2. Using basename() function
  3. Using substr() and strrpos() functions
  4. 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.

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.

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.

4. Using regular expression

Also, we can use the regular expression to get a filename without extension.

I hope you find this article helpful.
Thank you for reading. Happy Coding..!! 🙂

If you found value in this article,
you can support us by buying me a coffee! ☕

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *