In this article, we will explain to you how to remove file extension from filename in PHP. so we will give you a simple example of how to remove extension from string.
if you want to remove the file extension from the filename using PHP. for that there are many ways available and you can easily remove the file extension with PHP. so you can see our following example.
Using pathinfo() Function
If you want to remove the extension then you can use the pathinfo() function. it returns arrays such as directory name, basename, extension and filename.
Example
<?php $filename = 'filename.php'; $without_ext = pathinfo($filename, PATHINFO_FILENAME); echo $without_ext; ?>
Output
filename
Using substr() and strrpos()
If you want to remove the extension then you can use the substr() and strrpos() function. it returns the filename without extension in PHP.
Example
<?php $filename = 'filename.php'; $without_ext = substr($filename, 0, strrpos($filename, ".")); echo $without_ext; ?>
Output
filename
Using basename()
If you want to remove the extension then you can use the basename() function. it takes two arguments such as filename and extension. it is also returned filename without extension.
Example
<?php $filename = 'filename.php'; $without_ext= basename($filename, '.php'); echo $without_ext; ?>
Output
filename
Using Regular Expression
If you want to remove the extension then you can use regular expression. The regular expression to match the pattern and if match pattern then return the filename without extension.
Example
<?php $filename = 'filename.php'; $without_ext = preg_replace('/\\.[^.\\s]{3,4}$/', '', $filename); echo $without_ext; ?>
Output
filename