Frog82
Frog82

Reputation: 464

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

Upvotes: 0

Views: 1365

Answers (4)

msfoster
msfoster

Reputation: 2572

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;

Upvotes: 0

yanivel
yanivel

Reputation: 59

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

Upvotes: -1

Dannn
Dannn

Reputation: 316

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

Upvotes: 2

Hakim
Hakim

Reputation: 1102

you could try :

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

Upvotes: 0

Related Questions