PHP basename
Summary: in this tutorial, you will learn how to use the PHP basename()
function to get the trailing name component of a path.
Introduction to the PHP basename() function
The basename()
function returns the trailing name component of path:
basename ( string $path , string $suffix = "" ) : string
Code language: PHP (php)
The basename()
function has two parameters:
$path
is the file or directory path that you want to extract the trailing name component.$suffix
if the name component ends with the suffix, it will be stripped off.
The basename()
function returns the basename of a specific path.
On Windows, you can use both slash (/
) and backslash (\
) as the directory separator character. However, on other environments such as Linux, you can only use the forward-slash (/
).
To get all components of file or directory path, you can use the pathinfo()
function.
PHP basename() function example
The following example shows how to use the basename()
function to get the trailing name component of various paths:
echo "1) ".basename("/htdocs/index.php", ".php").PHP_EOL;
echo "2) ".basename("/htdocs/index.php").PHP_EOL;
echo "3) ".basename("/htdocs/public").PHP_EOL;
echo "4) ".basename("/htdocs/").PHP_EOL;
echo "5) ".basename(".").PHP_EOL;
echo "6) ".basename("/");
Code language: HTML, XML (xml)
Output:
1) index
2) index.php
3) public
4) htdocs
5) .
6)
Code language: CSS (css)
Summary
- Use the PHP
basename()
function to get the trailing name component of a file or directory path.