Reputation: 464
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
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
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 characters after last / in url
Upvotes: -1
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
Reputation: 1102
you could try :
$link = $_SERVER["REQUEST_URI"];
$link_array = explode('/',$link);
$lastPart = str_replace('/', '', $link_array[count($link_array) - 1]);
Upvotes: 0