简体   繁体   中英

Get End Part of URL Before Trailing Slash

I'm attempting to retrieve the last part of a URL before the trailing backslash. I have used this previously, which worked great, but the URL on the site I was developing back then did not have a trailing slash. Below is the code I used for that.

$link = $_SERVER["REQUEST_URI"];
$link_array = explode('/',$link);
echo $page = end($link_array);

Any help would be appreciated,

Kind Regards,

Rees

This works for me

$link = $_SERVER["REQUEST_URI"];
if(substr($link, -1) == '/') {
$link = substr($link, 0, -1);
}
$link_array = explode('/',$link);
echo $page = strtoupper(end($link_array));

you could try :

$link = $_SERVER["REQUEST_URI"];
$link_array = explode('/',$link);
$lastPart = str_replace('/', '', $link_array[count($link_array) - 1]);

You are almost there. You have to pick the second last value:

$link = $_SERVER["REQUEST_URI"];
$link_array = explode('/',$link);
end($link_array);//move cursor to the end
//pick last or second last depending on trailing slash
$page = substr($link,-1) == "/" ? prev($link_array) : current($link_array);
echo $page;

You can use php's parse_url to parse the url and get the wanted components.

or

EDIT:

$url = 'http://' . $_SERVER[HTTP_HOST] . $_SERVER[REQUEST_URI];
if (substr("url", -1) == '/') {
    rtrim($url , "/")
}
$lastPart = substr($url, strrpos($url, '/') + 1);

This is from Stackoverflow posts:

Get the full URL in PHP

Get characters after last / in 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