Get File Name Without File Extension in PHP

Definition and Usage - basename()
The basename() function returns the filename from a path.
Syntax
basename(path,suffix)

ParameterDescription
pathRequired. Specifies the path to check
suffixOptional. 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");
?>
The output of the code above will be:
home.php
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

Comments

Post a Comment

Popular Posts