PHP 8.4.2 Released!

basename

(PHP 4, PHP 5, PHP 7, PHP 8)

basename返回路径中的文件名部分

说明

basename(string $path, string $suffix = ""): string

给出一个包含有指向一个文件的全路径的字符串,本函数返回基本的文件名。

注意:

basename() 纯粹基于输入字符串操作, 它不会受实际文件系统和类似 ".." 的路径格式影响。

警告

basename() 是本地化的,所以如果要正确处理多字节字符的路径,需要用 setlocale() 正确设置匹配的 locale。如果 path 包含当前区域设置无效的字符,basename() 的行为未定义。

参数

path

一个路径。

在 Windows 中,斜线(/)和反斜线(\)都可以用作目录分隔符。在其它环境下是斜线(/)。

suffix

如果文件名是以 suffix 结束的,那这一部分也会被去掉。

返回值

返回指定 path 的基本名称。

示例

示例 #1 basename() 例子

<?php
echo "1) ".basename("/etc/sudoers.d", ".d").PHP_EOL;
echo
"2) ".basename("/etc/sudoers.d").PHP_EOL;
echo
"3) ".basename("/etc/passwd").PHP_EOL;
echo
"4) ".basename("/etc/").PHP_EOL;
echo
"5) ".basename(".").PHP_EOL;
echo
"6) ".basename("/");
?>

以上示例会输出:

1) sudoers
2) sudoers.d
3) passwd
4) etc
5) .
6)

参见

添加备注

用户贡献的备注 4 notes

up
53
Anonymous
7 years ago
It's a shame, that for a 20 years of development we don't have mb_basename() yet!

// works both in windows and unix
function mb_basename($path) {
if (preg_match('@^.*[\\\\/]([^\\\\/]+)$@s', $path, $matches)) {
return $matches[1];
} else if (preg_match('@^([^\\\\/]+)$@s', $path, $matches)) {
return $matches[1];
}
return '';
}
up
10
(remove) dot nasretdinov at (remove) dot gmail dot com
16 years ago
There is only one variant that works in my case for my Russian UTF-8 letters:

<?php
function mb_basename($file)
{
return
end(explode('/',$file));
}
><

It is intented for UNIX servers
up
4
KOmaSHOOTER at gmx dot de
19 years ago
If you want the current path where youre file is and not the full path then use this :)

<?php
echo('dir = '.basename (dirname($_SERVER['PHP_SELF']),"/"));
// retuns the name of current used directory
?>

Example:

www dir: domain.com/temp/2005/january/t1.php

<?php
echo('dirname <br>'.dirname($_SERVER['PHP_SELF']).'<br><br>');
// returns: /temp/2005/january
?>

<?php
echo('file = '.basename ($PHP_SELF,".php"));
// returns: t1
?>

if you combine these two you get this
<?php
echo('dir = '.basename (dirname($_SERVER['PHP_SELF']),"/"));
// returns: january
?>

And for the full path use this
<?php
echo(' PHP_SELF <br>'.$_SERVER['PHP_SELF'].'<br><br>');
// returns: /temp/2005/january/t1.php
?>
up
5
swedish boy
15 years ago
Here is a quick way of fetching only the filename (without extension) regardless of what suffix the file has.

<?php

// your file
$file = 'image.jpg';

$info = pathinfo($file);
$file_name = basename($file,'.'.$info['extension']);

echo
$file_name; // outputs 'image'

?>
To Top