2009-09-13 21 views

Respuesta

329

Está buscando basename.

El ejemplo del manual de 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" 
?> 
+21

nombre base() tiene un error cuando los personajes procesos asiáticos como el chino. –

+0

Gracias Sun, me acabas de ahorrar horas de matar insectos ya que mi aplicación se usará en el extranjero. – SilentSteel

+1

Muy buggy incluso ahora –

6
$filename = basename($path); 
10

La función basename debería darle lo que quiere:

Dada una cadena que contiene una ruta a un archivo , esta función devolverá el nombre base del archivo.

Por ejemplo, citando a la página del manual:

<?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" 
?> 

O, en su caso:

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

que obtendrá:

string(10) "Output.map" 
1

Para obtener el nombre exacto del archivo de la URI, me gustaría utilizar este método:

<?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, '?')); 
?> 
6

nombre base() tiene un error al procesar caracteres asiáticos como el chino.

utilizo este:

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

he hecho esto usando la función PATHINFO que crea una matriz con las partes de la ruta de acceso para su uso! Por ejemplo, usted puede hacer esto:

<?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); 
?> 

Esto devolverá:

/usr/admin/config 
test.xml 
xml 
test 

El uso de esta función ha estado disponible desde PHP 5.2.0!

Luego puede manipular todas las piezas que necesite. Por ejemplo, para usar la ruta completa, puede hacer esto:

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

Basename no funciona para mí. Obtuve el nombre de archivo de un formulario (archivo). En Google Chrome (Mac   OS   X   v10.7 (Lion)) se convierte en la variable de archivo:

c:\fakepath\file.txt 

Cuando uso:

basename($_GET['file']) 

vuelve:

c:\fakepath\file.txt 

Así que en este caso la respuesta Sun Junwen funciona mejor.

En Firefox, la variable del archivo no incluye este camino falso.

6

Con SplFileInfo:

clase SplFileInfo El SplFileInfo ofrece un objeto de alto nivel orientado interfaz a la información para un archivo individual.

Ref: http://php.net/manual/en/splfileinfo.getfilename.php

$info = new SplFileInfo('/path/to/foo.txt'); 
var_dump($info->getFilename()); 

O/P: string (7) "foo.txt"

4

Prueba esto:

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

¡Es sencillo. Por ejemplo:

<?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); 
?> 

La salida será:

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

Hay varias maneras de obtener el nombre de archivo y extensión. Puede usar el siguiente que es fácil de usar.

$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 
+0

@peter Mortensen Gracias por su apoyo –

1

Para hacer esto en las líneas de menor cantidad se recomienda usar la incorporada en DIRECTORY_SEPARATOR constante a lo largo de explode(delimiter, string) para separar la ruta en partes y luego simplemente arrancar el último elemento de la matriz proporcionada.

Ejemplo:

$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' 
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>

Cuestiones relacionadas