Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the last path in a URL?

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.

like image 937
bahamut100 Avatar asked Feb 16 '10 13:02

bahamut100


People also ask

How do I find the last path of a URL?

We identify the index of the last / in the path, calling lastIndexOf('/') on the thePath string. Then we pass that to the substring() method we call on the same thePath string. This will return a new string that starts from the position of the last / , + 1 (otherwise we'd also get the / back).


2 Answers

Try:

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

Assuming $tokens has at least 2 elements.

like image 169
Bart Kiers Avatar answered Sep 19 '22 14:09

Bart Kiers


Try this:

function getLastPathSegment($url) {     $path = parse_url($url, PHP_URL_PATH); // to get the path from a whole URL     $pathTrimmed = trim($path, '/'); // normalise with no leading or trailing slash     $pathTokens = explode('/', $pathTrimmed); // get segments delimited by a slash      if (substr($path, -1) !== '/') {         array_pop($pathTokens);     }     return end($pathTokens); // get the last segment }      echo getLastPathSegment($_SERVER['REQUEST_URI']); 

I've also tested it with a few URLs from the comments. I'm going to have to assume that all paths end with a slash, because I can not identify if /bob is a directory or a file. This will assume it is a file unless it has a trailing slash too.

echo getLastPathSegment('http://server.com/bla/wce/news.php'); // wce  echo getLastPathSegment('http://server.com/bla/wce/'); // wce  echo getLastPathSegment('http://server.com/bla/wce'); // bla 
like image 44
alex Avatar answered Sep 21 '22 14:09

alex