How to Remove Extension from Filename in PHP

To get only the name of a file, the extension needs to be removed from the filename. You can remove the extension from a filename with PHP. There is a number of ways to remove extension from a string using PHP. In the following example code, we will show you all the possible ways to remove the extension from the filename and extract the original name of the file in PHP.

Using Regular Expression (RegEx):
Use the RegEx pattern to remove extension from filename using PHP.

$filename 'filename.php'; 
$filename_without_ext preg_replace('/\\.[^.\\s]{3,4}$/'''$filename);

Using substr() and strrpos() Functions:
You can use the substr() and strrpos() functions to retrieve filename without extension in PHP.

$filename 'filename.php'; 
$filename_without_ext substr($filename0strrpos($filename"."));

Using pathinfo() Function:
The PHP pathinfo() function returns information about a file path (directory name, basename, extension and filename) in an array.

  • You can use the PATHINFO_FILENAME flag to strip extension and get the file name only.
$filename 'filename.php'; 
$filename_without_ext pathinfo($filenamePATHINFO_FILENAME);

Using basename() Function:
The PHP basename() function returns the filename of path.

  • If you already know the extension, pass it in the second optional parameter to strip that extension from filename.
$filename 'filename.php'; 
$filename_without_ext basename($filename'.php');

Leave a reply

keyboard_double_arrow_up