6

How to Remove Extension from Filename in PHP

 3 years ago
source link: https://www.codexworld.com/how-to/remove-extension-from-filename-in-php/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
Home  »  How To Guides  »  PHP   »   How to Remove Extension from Filename in PHP

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($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.

  • You can use the PATHINFO_FILENAME flag to strip extension and get the file name only.
$filename = 'filename.php'; 
$filename_without_ext = pathinfo($filename, PATHINFO_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

Cancel

Comment*

Your Name*

Your Email*

Your Website


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK