简体   繁体   中英

How to get URL last part with php

I was searching for solutions to display the current URL of the page, and I found a few ones but I don't know how to implement them and call them, so this was the best solution I've found for me because it already has the echo thingy.

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;
    }

And to call it, I'm calling it like this

echo curPageURL();

But I want to get only the last part of the URL, for exemple:

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

I want to get thequestion part of the URL. how can I do this?

As stated in the comments, the best way is to explode() then array_pop() your URL.

Like so:

function curPageURL() {

    $url = $_SERVER['REQUEST_URI'];
    $url = explode('/', $url);
    $lastPart = array_pop($url);

    return $lastPart;
}

@Vineet answer is suitable too.

In your case. Please change like

$url = curPageURL();

It will give you complete URL and then write lines as below

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

It will give your desired output.

您也可以尝试

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

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

PHP has a function called parse_url() that will ... parse an URL. What you are looking for is the path part of the result.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM