如何获取URL中的最后一个路径?

28

我想要获取URL中的最后一个路径片段:

  • http://blabla/bla/wce/news.php 或者
  • http://blabla/blablabla/dut2a/news.php

例如,在这两个URL中,我想要获取路径片段:'wce' 和 'dut2a'。

我尝试使用 $_SERVER['REQUEST_URI'] ,但是我获取到了整个URL路径。

9个回答

53

试试这个:

$url = 'http://blabla/blablabla/dut2a/news.php';
$tokens = explode('/', $url);
echo $tokens[sizeof($tokens)-2];

假设$tokens至少有两个元素。


如果这是正确的答案,那么您应该通过点击旁边的白色复选标记来接受它。bahamut100 - Mike Sherov
2
它不会处理:http://foobar.com/path/path#fragment/fragment - ddimitrov
@ddimitrov:是的,说得好。这更加证明了OP应该采用Alex的解决方案。但既然我的答案已被接受,就不能删除它... - Bart Kiers
碎片并不是问题,因为它们不会传递到服务器。然而,像这样的URL将是一个问题:http://www.example.com/dir1/dir2/foo?redirect=http://anothersite.com/default.aspx - eis

30

试试这个:

function getLastPathSegment($url) {
    $path = parse_url($url, PHP_URL_PATH); // to get the path from a whole URL
    $pathTrimmed = trim($path, '/'); // normalise with no leading or trailing slash
    $pathTokens = explode('/', $pathTrimmed); // get segments delimited by a slash

    if (substr($path, -1) !== '/') {
        array_pop($pathTokens);
    }
    return end($pathTokens); // get the last segment
}

    echo getLastPathSegment($_SERVER['REQUEST_URI']);

我还用评论中提供的一些URL进行了测试。我必须假设所有路径都以斜杠结尾,因为我无法确定/bob是目录还是文件。除非它也有尾随斜杠,否则这将假定它是一个文件。

echo getLastPathSegment('http://server.com/bla/wce/news.php'); // wce

echo getLastPathSegment('http://server.com/bla/wce/'); // wce

echo getLastPathSegment('http://server.com/bla/wce'); // bla

1
дҪҝз”Ёparse_urlд»…иҺ·еҸ–URLи·Ҝеҫ„еҖјжҳҜжӯЈзЎ®зҡ„пјҢдҪҶдҪ д№ҹйңҖиҰҒеҜ№$_SERVER['REQUEST_URI']жү§иЎҢзӣёеҗҢж“ҚдҪңгҖӮ - Gumbo
我以为 $_SERVER['REQUEST_URI'] 总是返回 something/like/this 这样的东西? - alex
@alex:不,PHP中也包含查询。因此URL路径和URL查询(如HTTP请求行)。 - Gumbo
@gumbo 感谢你的提示,我也为此编写了一个函数包装器。 - alex
在类似于/bla/wce/news.php这样的情况下,它不会像OP想要的那样返回wce,而是返回news.php。它应该返回倒数第二个元素而不是end()吧?我没有真正测试过,因为它需要PHP版本>=5.1.2,所以如果我有误请指正。 - andyk
@andyk 感谢光临。我对该函数进行了一些修改,并运行了您的字符串以及一些类似的字符串以获取它们各自的输出结果。 - alex

26

2
在此之前可能需要对URL进行一些过滤。否则会在类似于http://www.example.com/dir1/dir2/foo?redirect=http://anothersite.com/default.aspx的情况下失败。 - andyk
我只使用了basename()函数来解决它,在你的方式中,我在"retro"中获得了第二层。 - insign
1
basename($_SERVER['PHP_SELF']); 对我很有用。 - Niels
@insign 这正是原帖所问的。 - Andreas Bergström

13

试试这个:

 $parts = explode('/', 'your_url_here');
 $last = end($parts);

2
如果URL末尾有斜杠,则可能会失败。 - insign

1

另一个解决方案:

$last_slash = strrpos('/', $url);
$last = substr($url, $last_slash);

1:获取最后一个斜杠的位置 2:获取最后一个斜杠和字符串结尾之间的子字符串

看这里:测试


1
如果您想处理绝对URL,那么可以使用parse_url()(它不适用于相对URL)。
$url = 'http://aplicaciones.org/wp-content/uploads/2011/09/skypevideo-500x361.jpg?arg=value#anchor';
print_r(parse_url($url));
$url_path = parse_url($url, PHP_URL_PATH);
$parts = explode('/', $url_path);
$last = end($parts);
echo $last;

完整的代码示例在这里:http://codepad.org/klqk5o29


1
$arr =  explode("/", $uri);

这只是解决方案的一半,仅有代码的答案在Stackoverflow上价值不高。 - mickmackusa
1
@mickmackusa,你来晚了大约10年。有用的反馈。 - Gabe
我在志愿工作中不会因时间而歧视。新访客会阅读旧的低价值帖子并鼓励新的低价值帖子。我希望这个地方不断改进——无论内容有多老。请对这篇文章做点什么。 - mickmackusa

1

我写了一个小函数来获取url的最后一级目录/文件夹。它只适用于真实存在的url,而不是理论上的url。在我的情况下,这总是成立的,所以...

function uf_getLastDir($sUrl)
{
    $sPath = parse_url($sUrl, PHP_URL_PATH);   // parse URL and return only path component 
    $aPath = explode('/', trim($sPath, '/'));  // remove surrounding "/" and return parts into array
    end($aPath);                               // last element of array
    if (is_dir($sPath))                        // if path points to dir
        return current($aPath);                // return last element of array
    if (is_file($sPath))                       // if path points to file
        return prev($aPath);                   // return second to last element of array
    return false;                              // or return false
}

我也这么做了!享受吧!还要向之前的答案表示赞美!!!


0
这将保留最后一个斜线后面的部分。
不必担心explode,例如没有斜杠。
$url = 'http://blabla/blablabla/dut2a/news.php';
$url = preg_replace('~.*/~', '', $url);

会给予

news.php

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接