PHP 8.4.0 RC3 available for testing

basename

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

basenameRestituisce il nome del file dal percorso indicato

Descrizione

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

Data una stringa contenente il percorso di un file, questa funzione restituisce il nome del file. Se il nome del file finisce in suffix quest'ultimo verrà tagliato.

Su Windows, sia gli slash (/) che i backslash (\) vengono utilizzati come carattere di separazione delle directory. In altri ambienti, si usa solo lo slash semplice (/).

Example #1 Esempio di basename()

<?php
$path
= "/home/httpd/html/index.php";
$file = basename($path); // la variabile $file contiene "index.php"
$file = basename($path,".php"); // la variabile $file contiene "index"
?>

Nota:

Il parametro suffix è stato aggiunto in PHP 4.1.0.

Vedere anche dirname()

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