I would like get the last path segment in a URL:
http://blabla/bla/wce/news.php
orhttp://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.
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).
Try:
$url = 'http://blabla/blablabla/dut2a/news.php'; $tokens = explode('/', $url); echo $tokens[sizeof($tokens)-2];
Assuming $tokens
has at least 2 elements.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With