28

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.

Elijah Lynn
  • 12,272
  • 10
  • 61
  • 91
bahamut100
  • 1,795
  • 7
  • 27
  • 38

9 Answers9

53

Try:

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

Assuming $tokens has at least 2 elements.

Bart Kiers
  • 166,582
  • 36
  • 299
  • 288
  • bahamut100, If this is the right answer, then you should accept it by clicking the white checkmark next to it. – Mike Sherov Feb 16 '10 at 13:56
  • 2
    It will not handhe: http:/ /foobar.com/path/path#fragment/fragment – ddimitrov Feb 16 '10 at 14:11
  • @ddimitrov: yes, good point. The more reason for the OP to go with Alex' solution. Can't remove my answer though since it is the accepted answer... – Bart Kiers Feb 16 '10 at 14:24
  • fragments aren't really a problem as they won't carry over to server. However, an url like this would be a problem: `http://www.example.com/dir1/dir2/foo?redirect=http://anothersite.com/default.as‌​px` – eis Nov 26 '12 at 21:46
30

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
alex
  • 479,566
  • 201
  • 878
  • 984
  • 1
    +1 For using `parse_url` to get just the URL path. But you need to do that with `$_SERVER['REQUEST_URI']` as well. – Gumbo Feb 16 '10 at 13:59
  • I thought `$_SERVER['REQUEST_URI']` always came back with `something/like/this` ? – alex Feb 16 '10 at 14:03
  • @alex: No, in PHP it does also contain the query. So URL path and URL query (as in the HTTP request line). – Gumbo Feb 16 '10 at 14:13
  • @gumbo Thanks for the tip, I've made a function wrapper for it too. – alex Feb 16 '10 at 14:19
  • in something like this: `/bla/wce/news.php` wouldn't it return `news.php` instead of `wce` like the OP wanted? Shouldn't it returns the second last element instead of end()? I didn't really test this as it requires PHP version >= 5.1.2 so cmiiw. – andyk Feb 16 '10 at 15:24
  • @andyk Thanks for dropping by. I've made some modifications to the function, and run your string and some similar through for their respective outputs. – alex Feb 16 '10 at 23:27
26

it is easy

<?php
 echo basename(dirname($url)); // if your url/path includes a file
 echo basename($url); // if your url/path does not include a file
?>
  • basename will return the trailing trailing name component of path
  • dirname will return the parent directory's path

http://php.net/manual/en/function.dirname.php

http://php.net/manual/en/function.basename.php

Luca Reghellin
  • 7,426
  • 12
  • 73
  • 118
Stepan Suvorov
  • 25,118
  • 26
  • 108
  • 176
13

Try this:

 $parts = explode('/', 'your_url_here');
 $last = end($parts);
Sarfraz
  • 377,238
  • 77
  • 533
  • 578
1

I wrote myself a little function to get the last dir/folder of an url. It only works with real/existing urls, not theoretical ones. In my case, that was always the case, so ...

function uf_getLastDir($sUrl)
{
    $sPath = parse_url($sUrl, PHP_URL_PATH);   // parse URL and return only path component 
    $aPath = explode('/', trim($sPath, '/'));  // remove surrounding "/" and return parts into array
    end($aPath);                               // last element of array
    if (is_dir($sPath))                        // if path points to dir
        return current($aPath);                // return last element of array
    if (is_file($sPath))                       // if path points to file
        return prev($aPath);                   // return second to last element of array
    return false;                              // or return false
}

Works for me! Enjoy! And kudos to the previous answers!!!

maxpower9000
  • 223
  • 2
  • 8
1
$arr =  explode("/", $uri);
Gabe
  • 49,577
  • 28
  • 142
  • 181
  • This is only half of a solution and code-only answers are low value on Stackoverflow. – mickmackusa Dec 22 '19 at 01:30
  • 1
    @mickmackusa well you're about 10 years late to the party. Useful feedback. – Gabe Jan 06 '20 at 22:35
  • I do not discriminate in my volunteerism based on time. Old low-value posts get read by new visitors and encourage new low-value posts. I want this place to constantly improve -- no matter how old the content. Please do _something_ about this post. – mickmackusa Jan 06 '20 at 22:39
1

Another solution:

$last_slash = strrpos('/', $url);
$last = substr($url, $last_slash);

1: getting the last slash position 2: getting the substring between the last slash and the end of string

Look here: TEST

BCsongor
  • 869
  • 7
  • 11
1

If you want to process an absolute URL, then you can use parse_url() (it doesn't work with relative urls).

$url = 'http://aplicaciones.org/wp-content/uploads/2011/09/skypevideo-500x361.jpg?arg=value#anchor';
print_r(parse_url($url));
$url_path = parse_url($url, PHP_URL_PATH);
$parts = explode('/', $url_path);
$last = end($parts);
echo $last;

Full code example here: http://codepad.org/klqk5o29

julianm
  • 869
  • 8
  • 13
0

This will keep the part after the last slash.
No worries about explode, when for example no slash is there.

$url = 'http://blabla/blablabla/dut2a/news.php';
$url = preg_replace('~.*/~', '', $url);

Will give

news.php
Markus Zeller
  • 8,516
  • 2
  • 29
  • 35