PHPのお勉強!

PHP TOP

basename

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

basenameパスの最後にある名前の部分を返す

説明

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

ファイルあるいはディレクトリへのパスを含む文字列を受け取って、 最後にある名前の部分を返します。

注意:

basename() は、入力文字列を単純にそのまま処理します。 実際のファイルシステムを確認したり ".." のようなパスを気にしたりすることはありません。

警告

basename() はロケールに依存します。 マルチバイト文字を含むパスで正しい結果を得るには、それと一致するロケールを setlocale() で設定しておかなければなりません。 現在のロケールから見て不正な文字が 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)

参考

  • dirname() - 親ディレクトリのパスを返す
  • pathinfo() - ファイルパスに関する情報を返す

add a note

User Contributed Notes 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