How to get the last path in a URL?

bahamut100 picture bahamut100 · Feb 16, 2010 · Viewed 82.5k times · Source

I would like get the last path segment in a URL:

  • http://blabla/bla/wce/news.php or
  • http://blabla/blablabla/dut2a/news.php

For example, in these two URLs, I want to get the path segment: 'wce', and 'dut2a'.

I tried to use $_SERVER['REQUEST_URI'], but I get the whole URL path.

Answer

Bart Kiers picture Bart Kiers · Feb 16, 2010

Try:

$url = 'http://blabla/blablabla/dut2a/news.php';
$tokens = explode('/', $url);
echo $tokens[sizeof($tokens)-2];

Assuming $tokens has at least 2 elements.