Get Last Part of URL PHP

PhpUrl

Php Problem Overview


I'm just wondering how I can extract the last part of a URL using PHP.

The example URL is:

http://domain.com/artist/song/music-videos/song-title/9393903

Now how can I extract the final part using PHP?

9393903

There is always the same number of variables in the URL, and the id is always at the end.

Php Solutions


Solution 1 - Php

The absolute simplest way to accomplish this, is with basename()

echo basename('http://domain.com/artist/song/music-videos/song-title/9393903');

Which will print

> 9393903

Of course, if there is a query string at the end it will be included in the returned value, in which case the accepted answer is a better solution.

Solution 2 - Php

Split it apart and get the last element:

$end = end(explode('/', $url));
# or:
$end = array_slice(explode('/', $url), -1)[0];

Edit: To support apache-style-canonical URLs, rtrim is handy:

$end = end(explode('/', rtrim($url, '/')));
# or:
$end = array_slice(explode('/', rtrim($url, '/')), -1)[0];

A different example which might me considered more readable is (Demo):

$path = parse_url($url, PHP_URL_PATH);
$pathFragments = explode('/', $path);
$end = end($pathFragments);

This example also takes into account to only work on the path of the URL.


Yet another edit (years after), canonicalization and easy UTF-8 alternative use included (via PCRE regular expression in PHP):

<?php

use function call_user_func as f;
use UnexpectedValueException as e;

$url = 'http://example.com/artist/song/music-videos/song-title/9393903';

$result = preg_match('(([^/]*)/*$)', $url, $m)

    ? $m[1]
    : f(function() use ($url) {throw new e("pattern on '$url'");})
    ;

var_dump($result); # string(7) "9393903"

Which is pretty rough but shows how to wrap this this within a preg_match call for finer-grained control via PCRE regular expression pattern. To add some sense to this bare-metal example, it should be wrapped inside a function of its' own (which would also make the aliasing superfluous). Just presented this way for brevity.

Solution 3 - Php

You can use preg_match to match the part of the URL that you want.

In this case, since the pattern is easy, we're looking for a forward slash (\/ and we have to escape it since the forward slash denotes the beginning and end of the regular expression pattern), along with one or more digits (\d+) at the very end of the string ($). The parentheses around the \d+ are used for capturing the piece that we want: namely the end. We then assign the ending that we want ($end) to $matches[1] (not $matches[0], since that is the same as $url (ie the entire string)).

$url='http://domain.com/artist/song/music-videos/song-title/9393903';

if(preg_match("/\/(\d+)$/",$url,$matches))
{
  $end=$matches[1];
}
else
{
  //Your URL didn't match.  This may or may not be a bad thing.
}

Note: You may or may not want to add some more sophistication to this regular expression. For example, if you know that your URL strings will always start with http:// then the regex can become /^http:\/\/.*\/(\d+)$/ (where .* means zero or more characters (that aren't the newline character)).

Solution 4 - Php

If you are looking for a robust version that can deal with any form of URLs, this should do nicely:

<?php

$url = "http://foobar.com/foo/bar/1?baz=qux#fragment/foo";
$lastSegment = basename(parse_url($url, PHP_URL_PATH));

Solution 5 - Php

$id = strrchr($url,"/");
$id = substr($id,1,strlen($id));

Here is the description of the strrchr function: http://www.php.net/manual/en/function.strrchr.php

Hope that's useful!

Solution 6 - Php

Another option:

$urlarray=explode("/",$url);
$end=$urlarray[count($urlarray)-1];

Solution 7 - Php

One of the most elegant solutions was here https://stackoverflow.com/questions/1361741/get-characters-after-last-in-url

by DisgruntledGoat

$id = substr($url, strrpos($url, '/') + 1);

> strrpos gets the position of the last occurrence of the slash; substr > returns everything after that position.

Solution 8 - Php

One liner: $page_path = end(explode('/', trim($_SERVER['REQUEST_URI'], '/')));

Get URI, trim slashes, convert to array, grab last part

Solution 9 - Php

A fail safe solution would be:

Referenced from https://stackoverflow.com/a/2273328/2062851

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']); //9393903

Solution 10 - Php

this will do the job easily to get the last part of the required URL

$url="http://domain.com/artist/song/music-videos/song-title/9393903";
$requred_string= substr(strrchr($url, "/"), 1);

this will get you the string after first "/" from the right.

Solution 11 - Php

$mylink = $_SERVER['PHP_SELF'];
$link_array = explode('/',$mylink);
echo $lastpart = end($link_array);

Solution 12 - Php

function getLastPathSegment($url) {
    $arr = explode('/', $url);
    return $arr[count($arr) - 1];
}

Solution 13 - Php

1-liner

$end = preg_replace( '%^(.+)/%', '', $url );

// if( ! $end ) no match.

This simply removes everything before the last slash, including it.

Solution 14 - Php

One line working answer:

$url = "http://www.yoursite/one/two/three/drink";
echo $end = end((explode('/', $url)));

Output: drink

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionBelgin FishView Question on Stackoverflow
Solution 1 - Phpnikc.orgView Answer on Stackoverflow
Solution 2 - PhphakreView Answer on Stackoverflow
Solution 3 - Phpuser554546View Answer on Stackoverflow
Solution 4 - PhpPeterView Answer on Stackoverflow
Solution 5 - PhpTamer ShlashView Answer on Stackoverflow
Solution 6 - PhpsomeoneView Answer on Stackoverflow
Solution 7 - PhpRobert SinclairView Answer on Stackoverflow
Solution 8 - PhpJustinView Answer on Stackoverflow
Solution 9 - PhpsamjcoView Answer on Stackoverflow
Solution 10 - PhpXxANxXView Answer on Stackoverflow
Solution 11 - PhpShuhad zamanView Answer on Stackoverflow
Solution 12 - PhpTusharView Answer on Stackoverflow
Solution 13 - PhpJorge Orpinel PérezView Answer on Stackoverflow
Solution 14 - PhpGeorge ChalhoubView Answer on Stackoverflow