Get File Name Without File Extension in PHP
Definition and Usage - basename()
The basename() function returns the filename from a path.
Syntax
Example
You have to know the extension to remove it in advance though.
You can use pathinfo() and basename() together if you don't know the extension of the file.
First get the extension using pathinfo(), and use the basename function, like this:
pathinfo() returns information about path: either an associative array or a string, depending on options.
2. If the path does not have an extension, no extension element will be returned.
Ref: http://www.w3schools.com/php/func_filesystem_basename.asp and http://de.php.net/manual/en/function.pathinfo.php
The basename() function returns the filename from a path.
Syntax
basename(path,suffix)
Parameter | Description |
---|---|
path | Required. Specifies the path to check |
suffix | Optional. Specifies a file extension. If the filename has this file extension, the file extension will not show |
Example
<?php
$path = "/testweb/home.php";
//Show filename with file extension
echo basename($path) ."<br/>";
//Show filename without file extension
echo basename($path,".php");
?>
$path = "/testweb/home.php";
//Show filename with file extension
echo basename($path) ."<br/>";
//Show filename without file extension
echo basename($path,".php");
?>
The output of the code above will be:
home.php
home
home
You have to know the extension to remove it in advance though.
You can use pathinfo() and basename() together if you don't know the extension of the file.
First get the extension using pathinfo(), and use the basename function, like this:
$path = "/testweb/home.php";
$ext = pathinfo($path, PATHINFO_EXTENSION);
$file = basename($path, ".".$ext); // $file is set to "home"
Definition and Usage - pathinfo()pathinfo() returns information about path: either an associative array or a string, depending on options.
Note:
1. If the path has more than one an extension, PATHINFO_EXTENSION returns only the last one and PATHINFO_FILENAME only strips the last one.2. If the path does not have an extension, no extension element will be returned.
Ref: http://www.w3schools.com/php/func_filesystem_basename.asp and http://de.php.net/manual/en/function.pathinfo.php
Thanks for the answer it helped me a lot
ReplyDelete