PHP 8.6.0 Beta 1 is available for testing

basename

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

basenameDevuelve el nombre del componente final de una ruta

Descripción

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

Toma como argumento path, la ruta de un fichero o directorio y proporciona el nombre del último componente.

Nota:

basename() actúa de manera ingenua y no tiene conocimiento del sistema de archivos subyacente o de los componentes de una ruta tales como "..".

Precaución

basename() es sensible a la configuración local, por lo que si la ruta contiene caracteres multioctetos, la configuración local adecuada debe ser establecida mediante la función setlocale() . Si path contiene caracteres que son inválidos para la configuración local actual, el comportamiento de basename() es indefinido.

Parámetros

path

Una ruta.

En Windows, los caracteres slash (/) y backslash (\) se utilizan como separadores de directorio. En otros sistemas operativos, solo el carácter slash (/) se utiliza.

suffix

Si suffix es proporcionado, el sufijo también será eliminado.

Valores devueltos

Devuelve el nombre base de la ruta path dada.

Ejemplos

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

El ejemplo anterior mostrará:

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

Véase también

  • dirname() - Devuelve la ruta de la carpeta padre
  • pathinfo() - Devuelve información sobre una ruta del sistema

Found A Problem?

Learn How To Improve This PageSubmit a Pull RequestReport a Bug
+add a note

User Contributed Notes 5 notes

up
55
Anonymous
9 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
17
(remove) dot nasretdinov at (remove) dot gmail dot com
17 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
9
swedish boy
16 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
0
bobray at softville dot com
1 year ago
You might expect that echo basename('directory_name/') would return an empty string. Instead, it returns 'directory_name', without the slash.
up
-1
KOmaSHOOTER at gmx dot de
21 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 
?>
+add a note

AltStyle によって変換されたページ (->オリジナル) /