如何使用PHP从完整路径中获取文件名?

2022-08-30 06:08:44

例如,我如何获得Output.map

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

使用 PHP?


答案 1

您正在查找基名

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

答案 2

我已经使用函数完成了此操作,该函数创建了一个数组,其中包含路径的各个部分供您使用!例如,您可以执行以下操作:PATHINFO

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

这将返回:

/usr/admin/config
test.xml
xml
test

此功能的使用自 PHP 5.2.0 起可用!

然后,您可以根据需要操作所有部件。例如,要使用完整路径,可以执行以下操作:

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

推荐