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

bah*_*100 27 php url-parsing

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

  • http://blabla/bla/wce/news.php 要么
  • http://blabla/blablabla/dut2a/news.php

例如,在这两个URL中,我想获得路径段:'wce'和'dut2a'.

我尝试使用$_SERVER['REQUEST_URI'],但我得到了整个URL路径.

Bar*_*ers 51

尝试:

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

假设$tokens至少有2个元素.

  • 它不会递交:http:/ /foobar.com/path/path#fragment/fragment (2认同)

ale*_*lex 27

试试这个:

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']);
Run Code Online (Sandbox Code Playgroud)

我还用评论中的几个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
Run Code Online (Sandbox Code Playgroud)


Ste*_*rov 22

这很容易

<?php
 echo basename(dirname($url)); // if your url/path includes a file
 echo basename($url); // if your url/path does not include a file
?>
Run Code Online (Sandbox Code Playgroud)
  • basename 将返回路径的尾随尾随名称组件
  • dirname 将返回父目录的路径

http://php.net/manual/en/function.dirname.php

http://php.net/manual/en/function.basename.php

  • 在此之前可以对网址进行一些过滤。将在类似“http://www.example.com/dir1/dir2/foo?redirect=http://anothersite.com/default.aspx”的情况下失败 (2认同)

Sar*_*raz 9

试试这个:

 $parts = explode('/', 'your_url_here');
 $last = end($parts);
Run Code Online (Sandbox Code Playgroud)

  • 如果URL带有斜杠,则失败 (2认同)