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($filename, 0, strrpos($filename, "."));
Using pathinfo() Function:
The PHP pathinfo()
function returns information about a file path (directory name, basename, extension and filename) in an array.
$filename = 'filename.php';
$filename_without_ext = pathinfo($filename, PATHINFO_FILENAME);
Using basename() Function:
The PHP basename()
function returns the filename of path.
$filename = 'filename.php';
$filename_without_ext = basename($filename, '.php');