如何使用php获取URL的最后一部分


How to get URL last part with php

我在搜索显示页面当前URL的解决方案,我找到了一些,但我不知道如何实现和调用它们,所以这是我找到的最好的解决方案。

function curPageURL() {
     $pageURL = 'http';
     if ($_SERVER["HTTPS"] == "on") {$pageURL .= "s";}
     $pageURL .= "://";
     if ($_SERVER["SERVER_PORT"] != "80") {
      $pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
     } else {
      $pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
     }
     return $pageURL;
    }

我称之为

echo curPageURL();

但我只想得到URL的最后一部分,例如:

http://stackoverflow.com/posts/29237151/thequestion

我想获取URL的thequestion部分。我该怎么做?

如注释所述,最好的方法是先explode(),然后array_pop()您的URL。

像这样:

function curPageURL() {
    $url = $_SERVER['REQUEST_URI'];
    $url = explode('/', $url);
    $lastPart = array_pop($url);
    return $lastPart;
}

@葡萄藤的答案也很合适。

在您的案例中。请像一样更改

$url = curPageURL();

它会给你完整的网址,然后写行如下

$new = explode("/", $url);
$last_part = end($new);

它将提供您想要的输出。

你也可以试试

echo substr(strrchr(curPageURL(), "/"), 1);

http://php.net/manual/en/function.parse-url.php

PHP有一个名为parse_url()的函数,它将。。。解析URL。您要查找的是结果的path部分。

<?php
$url = 'http://stackoverflow.com/posts/29237151/thequestion?arg=value#anchor';
$pathParts = parse_url($url, PHP_URL_PATH);
$lastPart = array_pop(explode('/',  $pathParts));
echo $lastPart;

我认为最短的方法是:

end(explode('/',  $url));