Como faço para obter um nome de arquivo de um caminho completo com PHP?
Pergunta
Por exemplo, como faço para obter Output.map
F:\Program Files\SSH Communications Security\SSH Secure Shell\Output.map
com PHP?
Solução
Você está procurando basename
.
O exemplo do PHP 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"
?>
Outras dicas
Eu fiz isso usando o PATHINFO
função que cria uma matriz com as partes do caminho para você usar! Por exemplo, você pode fazer isso:
<?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);
?>
Isso irá retornar:
/usr/admin/config
test.xml
xml
test
O uso desta função está disponível desde PHP 5.2.0!
Em seguida, você pode manipular todas as peças que você precisa. Por exemplo, para usar o caminho completo, você pode fazer isso:
$fullPath = $xmlFile['dirname'] . '/' . $xmlSchema['basename'];
A função basename
deve dar-lhe o que você quer:
Dada uma string contendo um caminho para um arquivo, esta função irá retornar o nome de base do arquivo.
Por exemplo, citando a página do 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"
?>
Ou, no seu caso:
$full = 'F:\Program Files\SSH Communications Security\SSH Secure Shell\Output.map';
var_dump(basename($full));
Você vai ter:
string(10) "Output.map"
Com SplFileInfo :
ofertas de classe SplFileInfo O SplFileInfo orientadas a objeto de alto nível interface com informações para um arquivo 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"
Existem várias maneiras de obter o nome do arquivo e extensão. Você pode usar o seguinte que é 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
$filename = basename($path);
Tente isto:
echo basename($_SERVER["SCRIPT_FILENAME"], '.php')
basename () tem um erro no processamento de caracteres asiáticos como o chinês.
Eu uso este:
function get_basename($filename)
{
return preg_replace('/^.+[\\\\\\/]/', '', $filename);
}
Para fazer isso nas linhas de menor número, sugiro usar o built-in constante DIRECTORY_SEPARATOR
juntamente com explode(delimiter, string)
para separar o caminho em partes e, em seguida, simplesmente arrancar fora do último elemento na matriz fornecida.
Exemplo:
$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'
Você pode usar o basename () função .
Para obter o nome exato do arquivo a partir da URI, gostaria de usar 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, '?'));
?>
baseName não funciona para mim. Eu tenho o nome do arquivo a partir de um formulário (arquivo). No Google Chrome (Mac OS X versão 10.7 (Lion)) a variável de arquivo torna-se:
c:\fakepath\file.txt
Quando eu uso:
basename($_GET['file'])
ela retorna:
c:\fakepath\file.txt
Portanto, neste caso a resposta Sun Junwen funciona melhor.
No Firefox variável do arquivo não inclui esta fakepath.
<?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>
É simples. Por exemplo:
<?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);
?>
A saída será:
Array
(
[dirname] => /www/htdocs
[basename] => index.html
[extension] => html
[filename] => index
)
$image_path = "F:\Program Files\SSH Communications Security\SSH Secure Shell\Output.map";
$arr = explode('\\',$image_path);
$name = end($arr);