php |
How to remove an extension from a filename in PHP
In this article, we will explain to you how to remove an extension from a filename in PHP.
$filename = "myfilename.php";
$without_ext = pathinfo($filename, PATHINFO_FILENAME);
echo $without_ext;
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.
$filename = "myfilename.php";
$without_ext = pathinfo($filename, PATHINFO_FILENAME);
echo $without_ext;
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.
$filename = "myfilename.php";
$without_ext = basename($filename, `.php`);
echo $without_ext;
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.
$filename = `myfilename.php`;
$without_ext = substr($filename, 0, strrpos($filename, "."));
echo $without_ext;
4. Using regular expression
Also, we can use the regular expression to get a filename without extension.
$filename = `myfilename.php`;
$without_ext = preg_replace(`/.[^.]*$/`, ', $filename);
echo $without_ext;