How to remove extension from filename in PHP
In this article, We will share with you how to extract the filename extension in PHP, along with understanding their implementation through the examples. There are many ways to extract the extension from a filename with PHP, which is given below:
The strrpos() function finds the position of the last occurrence of a string inside another string.
Example: Using strrpos() Functions:
1 2 3 4 5 6 |
<?php // strrpos $filename = 'filename.html'; $withoutExt = substr($filename, 0, strrpos($filename, ".")); echo $withoutExt; ?> |
The pathinfo() function returns information about a file path.
Example: Using pathinfo() Function:
1 2 3 4 5 |
<?php $filename = 'filename.html'; $withoutExt = pathinfo($filename, PATHINFO_FILENAME); echo $withoutExt; ?> |
The PHP basename() function returns the filename of path.
Example: Using basename() Function:
1 2 3 4 5 |
<?php $filename = 'filename.html'; $withoutExt = basename($filename, '.html'); echo $withoutExt; ?> |
Using preg_replace() function: Using regular expressions like replace and search.
Example: Using Regular Expression:
1 2 3 4 5 6 |
<?php // Regular Expression $filename = 'filename.html'; $withoutExt = preg_replace('/\\.[^.\\s]{3,4}$/', '', $filename); echo $withoutExt; ?> |