basename

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

basenameRetorna a última parte do caminho

Descrição

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

Dada uma string contendo o caminho para um arquivo ou diretório, esta função retornará a última parte do caminho.

Nota:

A função basename() opera de forma ingênua na string fornecida e não tem conhecimento do sistema de arquivos real ou dos componentes de caminho como "..".

Cuidado

A função basename() reconhece a localidade, portanto, para obter o nome correto ao usar caminhos com caracteres multibyte, a localidade correspondente deve ser definida com a função setlocale(). Se o parâmetro path contiver caracteres inválidos para a localidade atual, o comportamento de basename() será indefinido.

Parâmetros

path

Um caminho.

No Windows, tanto a barra (/) quanto a barra invertida (\) são usadas como caractere separador de diretório. Em outros ambientes, apenas a barra (/) é usada.

suffix

Se a última parte do caminho terminar em suffix, ele será removido.

Valor Retornado

Retorna a última parte de um dado path.

Exemplos

Exemplo #1 Exemplo de 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("/");
?>

O exemplo acima produzirá:

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

Veja Também

  • dirname() - Retorna o caminho para o diretório pai
  • pathinfo() - Retorna informações sobre um caminho de arquivo

adicione uma nota

Notas Enviadas por Usuários (em inglês) 4 notes

up
55
Anonymous
8 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 unixfunction mb_basename($path) {    if (preg_match('@^.*[\\\\/]([^\\\\/]+)$@s', $path, $matches)) {        return $matches[1];    } else if (preg_match('@^([^\\\\/]+)$@s', $path, $matches)) {        return $matches[1];    }    return '';}
up
11
(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
3
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'?>
up
1
KOmaSHOOTER at gmx dot de
20 years ago
If you want the current path where youre file is and not the full path then use this :)<?phpecho('dir = '.basename (dirname($_SERVER['PHP_SELF']),"/"));    // retuns the name of current used directory?>Example: www dir: domain.com/temp/2005/january/t1.php<?phpecho('dirname <br>'.dirname($_SERVER['PHP_SELF']).'<br><br>');    // returns: /temp/2005/january?><?phpecho('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    ?>
To Top