0

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

Frog82
  • 464
  • 1
  • 8
  • 25

4 Answers4

2

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));
Dannn
  • 318
  • 1
  • 7
0

you could try :

$link = $_SERVER["REQUEST_URI"];
$link_array = explode('/',$link);
$lastPart = str_replace('/', '', $link_array[count($link_array) - 1]);
Hakim
  • 1,084
  • 11
  • 28
0

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;
msfoster
  • 2,474
  • 1
  • 17
  • 19
-1

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

Community
  • 1
  • 1
yanivel
  • 59
  • 3
  • We didn't fully understand what part of the url you wanted. For example the url: www.example.com/a/b/c/d.php : Do you need "d.php" or "a/b/c/d.php". – yanivel Feb 26 '15 at 15:14
  • example.com/one/two/ This would be the structure, and I would want two, without the trailing backslash @yanivel – Frog82 Feb 26 '15 at 15:15