How to Remove file Extension from Filename in PHP
In this article, we will explain to you how to remove file extension from filename in PHP. 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
1 2 3 4 5 | <?php $filename = 'filename.php'; $without_ext = pathinfo($filename, PATHINFO_FILENAME); echo $without_ext; ?> |
Output
1 | 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
1 2 3 4 5 | <?php $filename = 'filename.php'; $without_ext = substr($filename, 0, strrpos($filename, ".")); echo $without_ext; ?> |
Output
1 | 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
1 2 3 4 5 | <?php $filename = 'filename.php'; $without_ext= basename($filename, '.php'); echo $without_ext; ?> |
Output
1 | 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
1 2 3 4 5 | <?php $filename = 'filename.php'; $without_ext = preg_replace('/\\.[^.\\s]{3,4}$/', '', $filename); echo $without_ext; ?> |
Output
1 | filename |
Read Also
Login And Registration Example Using Pdo
How To Add Days To Current Date In Php
How to remove duplicate values from an array in PHP