Clue Mediator

How to remove an extension from a filename in PHP

๐Ÿ“…June 23, 2021
๐Ÿ—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

  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.

<!--?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.

<!--?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.

<!--?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.

<!--?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..!! ๐Ÿ™‚