仅获取扩展名为 URL 的文件名,而不是 PHP 中的文件夹目录名称

Get Only File Name With Extension From URL Not Folder Directory Name In PHP

我想使用 PHP 从当前 URL 获取扩展名的文件名。对于这个问题,网上有很多代码,但到目前为止,其中 none 已经满足了我的需要。这是最常用的代码,但仍然没有满足我的要求。

好吧,我需要的是作为示例,我在下面分享了一些 URLS 并希望得到想要的结果。

URL: https://www.example.gov.us/directory_1/directory_2/directory_3/index.php

Outcome Needed: index.php

URL: https://www.example.gov.us/directory_1/directory_2/directory_3/index //Extension removed via .htaccess

Outcome Needed: index

URL: https://www.example.gov.us/directory_1/directory_2/directory_3/

Outcome Needed: [Empty]

为此,我使用了以下代码...

$actual_link = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
$path_parts = pathinfo($actual_link);
echo $path_parts['dirname'];
echo $path_parts['basename'];
echo $path_parts['extension'];
echo $path_parts['filename'];

但是我从上面的代码中收到了以下输出。

// Correct Output
$actual_link = "https://www.example.gov.us/directory_1/directory_2/directory_3/index.php";
$path_parts = pathinfo($actual_link);
echo $path_parts['dirname'];  //https://www.example.gov.us/directory_1/directory_2/directory_3
echo $path_parts['basename'];  //index.php
echo $path_parts['extension'];  //php
echo $path_parts['filename'];  //index

// Incorrect Output
$actual_link = "https://www.example.gov.us/directory_1/directory_2/directory_3/index";
$path_parts = pathinfo($actual_link);
echo $path_parts['dirname'];  //https://www.example.gov.us/directory_1/directory_2/directory_3
echo $path_parts['basename'];  //index
echo $path_parts['extension'];  //Notice: Undefined index: extension
echo $path_parts['filename'];  //index

// Incorrect Output
$actual_link = "https://www.example.gov.us/directory_1/directory_2/directory_3/";
$path_parts = pathinfo($actual_link);
echo $path_parts['dirname'];  //https://www.example.gov.us/directory_1/directory_2
echo $path_parts['basename'];  //directory_3
echo $path_parts['extension'];  //Notice: Undefined index: extension
echo $path_parts['filename'];  //directory_3

最后一种情况使此代码无法使用,所以有没有其他方法可以让我在上面的所有 3 种情况下获取带扩展名的文件名?

问题是目录的base-name是目录。

我认为您需要针对第三种情况使用一些自定义逻辑

$outcome = str_ends_with($actual_link, "/") ? "" : basename($actual_link);

str_ends_with() 是一个 PHP 8 函数。如果您需要对旧版本的支持,请使用此 polyfill

if (!function_exists("str_ends_with")) {
    function str_ends_with($haystack, $needle) {
        return strrpos($haystack, $needle) === strlen($haystack) - strlen($needle);
    }
}

演示~https://3v4l.org/qQiOq