Come posso ottenere un nome file da un percorso completo con PHP?


229

Ad esempio, come ottengo Output.map

a partire dal

F:\Program Files\SSH Communications Security\SSH Secure Shell\Output.map

con PHP?

Risposte:


451

Stai cercando basename.

L'esempio del manuale di PHP:

<?php
$path = "/home/httpd/html/index.php";
$file = basename($path);         // $file is set to "index.php"
$file = basename($path, ".php"); // $file is set to "index"
?>

29
basename () ha un bug quando elabora caratteri asiatici come il cinese.
— Sun Junwen

1
Grazie Sun, mi hai appena salvato ore di uccisioni di bug poiché la mia app verrà utilizzata all'estero.
— SilentSteel

11
Vorrei suggerire pathinfosopra basenamecome Metafaniel postato qui sotto. pathinfo()ti darà un array con le parti del percorso. O per il caso qui, puoi semplicemente chiedere il nome del file. Quindi pathinfo('/var/www/html/index.php', PATHINFO_FILENAME)dovrebbe restituire la 'index.php' documentazione PHP Pathinfo
— OnethingSimple

7
@OnethingSimple Controlla di nuovo i documenti ... nonostante sia intuitivo, ti consigliamo PATHINFO_BASENAMEdi ottenere il massimo index.php. PATHINFO_FILENAMEti darà index.
— levigroker,

1
in ogni caso, per un metodo compatibile con Unicode, mb_substr($filepath,mb_strrpos($filepath,'/',0,'UTF-16LE'),NULL,'UTF-16LE')basta sostituire UTF-16LE con qualunque set di caratteri utilizzato dal proprio filesystem (NTFS ed ExFAT usano UTF16)
— hanshenrik

68

L'ho fatto usando la funzione PATHINFOche crea un array con le parti del percorso che puoi usare! Ad esempio, puoi farlo:

<?php
    $xmlFile = pathinfo('/usr/admin/config/test.xml');

    function filePathParts($arg1) {
        echo $arg1['dirname'], "\n";
        echo $arg1['basename'], "\n";
        echo $arg1['extension'], "\n";
        echo $arg1['filename'], "\n";
    }

    filePathParts($xmlFile);
?>

Questo restituirà:

/usr/admin/config
test.xml
xml
test

L'uso di questa funzione è disponibile da PHP 5.2.0!

Quindi puoi manipolare tutte le parti di cui hai bisogno. Ad esempio, per utilizzare il percorso completo, è possibile effettuare ciò:

$fullPath = $xmlFile['dirname'] . '/' . $xmlFile['basename'];

1
Questo mi ha aiutato, buona risposta.
— Wiki Babu,

12

La basenamefunzione dovrebbe darti quello che vuoi:

Data una stringa contenente un percorso a un file, questa funzione restituirà il nome base del file.

Ad esempio, citando la pagina del manuale:

<?php
    $path = "/home/httpd/html/index.php";
    $file = basename($path);         // $file is set to "index.php"
    $file = basename($path, ".php"); // $file is set to "index"
?>

Oppure, nel tuo caso:

$full = 'F:\Program Files\SSH Communications Security\SSH Secure Shell\Output.map';
var_dump(basename($full));

Otterrai:

string(10) "Output.map"

12

Esistono diversi modi per ottenere il nome e l'estensione del file. È possibile utilizzare il seguente che è facile da usare.

$url = 'http://www.nepaltraveldoor.com/images/trekking/nepal/annapurna-region/Annapurna-region-trekking.jpg';
$file = file_get_contents($url); // To get file
$name = basename($url); // To get file name
$ext = pathinfo($url, PATHINFO_EXTENSION); // To get extension
$name2 =pathinfo($url, PATHINFO_FILENAME); // File name without extension

@peter Mortensen Grazie per il tuo supporto
— Khadka Pushpendra,


9

Prova questo:

echo basename($_SERVER["SCRIPT_FILENAME"], '.php') 

8

basename () presenta un bug durante l'elaborazione di caratteri asiatici come il cinese.

Io lo uso questo:

function get_basename($filename)
{
    return preg_replace('/^.+[\\\\\\/]/', '', $filename);
}

Non credo che la sua bug una, nei documenti la sua menzionati: Caution basename() is locale aware, so for it to see the correct basename with multibyte character paths, the matching locale must be set using the setlocale() function. . Ma preferisco anche usare preg_replace, perché il separatore di directory differisce tra i sistemi operativi. Su Ubuntu `\` non è un separatore diretto e basename non avrà alcun effetto su di esso.
— Adam,


4

Per fare ciò con il minor numero di righe suggerirei di utilizzare la DIRECTORY_SEPARATORcostante incorporata insieme explode(delimiter, string)a separare il percorso in parti e quindi semplicemente rimuovere l'ultimo elemento nell'array fornito.

Esempio:

$path = 'F:\Program Files\SSH Communications Security\SSH SecureShell\Output.map'

//Get filename from path
$pathArr = explode(DIRECTORY_SEPARATOR, $path);
$filename = end($pathArr);

echo $filename;
>> 'Output.map'


1

Per ottenere il nome esatto del file dall'URI, utilizzare questo metodo:

<?php
    $file1 =basename("http://localhost/eFEIS/agency_application_form.php?formid=1&task=edit") ;

    //basename($_SERVER['REQUEST_URI']); // Or use this to get the URI dynamically.

    echo $basename = substr($file1, 0, strpos($file1, '?'));
?>

0
<?php

  $windows = "F:\Program Files\SSH Communications Security\SSH Secure Shell\Output.map";

  /* str_replace(find, replace, string, count) */
  $unix    = str_replace("\\", "/", $windows);

  print_r(pathinfo($unix, PATHINFO_BASENAME));

?> 

body, html, iframe { 
  width: 100% ;
  height: 100% ;
  overflow: hidden ;
}
<iframe src="https://ideone.com/Rfxd0P"></iframe>


0

È semplice. Per esempio:

<?php
    function filePath($filePath)
    {
        $fileParts = pathinfo($filePath);

        if (!isset($fileParts['filename']))
        {
            $fileParts['filename'] = substr($fileParts['basename'], 0, strrpos($fileParts['basename'], '.'));
        }
        return $fileParts;
    }

    $filePath = filePath('/www/htdocs/index.html');
    print_r($filePath);
?>

L'output sarà:

Array
(
    [dirname] => /www/htdocs
    [basename] => index.html
    [extension] => html
    [filename] => index
)

0
$image_path = "F:\Program Files\SSH Communications Security\SSH Secure Shell\Output.map";
$arr = explode('\\',$image_path);
$name = end($arr);

Descrivi cosa hai cambiato e perché, per aiutare gli altri a identificare il problema e capire questa risposta
— FZ
Utilizzando il nostro sito, riconosci di aver letto e compreso le nostre Informativa sui cookie e Informativa sulla privacy.
Licensed under cc by-sa 3.0 with attribution required.