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
- Formatting number using the number_format() function in PHP
- Load More data from the database using AJAX, jQuery in PHP with MySQL
- How to implement jQuery select2 multiple select plugin in PHP
- Google reCAPTCHA v3 in PHP
- How to get a file extension in 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.
<!--?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..!! ๐