Belgin Fish
Belgin Fish

Reputation: 19857

Get Last Part of URL PHP

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

The example URL is:

http://domain.example/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.

Upvotes: 85

Views: 153741

Answers (15)

darthvader666uk
darthvader666uk

Reputation: 5

This works Perfectly. I tweaked it so I can use REQUEST_URI:

substr($_SERVER['REQUEST_URI'], strrpos($_SERVER['REQUEST_URI'], '/') + 1);

Upvotes: 0

nikc.org
nikc.org

Reputation: 16993

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

echo basename('http://example.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.

Upvotes: 190

XxANxX
XxANxX

Reputation: 121

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

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

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

Upvotes: 1

Tamer Shlash
Tamer Shlash

Reputation: 9523

$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

Upvotes: 15

Peter
Peter

Reputation: 31771

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

<?php

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

Upvotes: 32

user554546
user554546

Reputation:

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.example/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)).

Upvotes: 28

Tushar
Tushar

Reputation: 23

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

Upvotes: 1

samjco-com
samjco-com

Reputation: 409

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

Upvotes: 3

hakre
hakre

Reputation: 198219

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.

Upvotes: 109

Robert Sinclair
Robert Sinclair

Reputation: 5446

One of the most elegant solutions was here 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.

Upvotes: 6

Justin
Justin

Reputation: 27331

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

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

Upvotes: 3

Shuhad zaman
Shuhad zaman

Reputation: 3390

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

Upvotes: 1

Online User
Online User

Reputation: 17808

One line working answer:

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

Output: drink

Upvotes: 0

Jorge Orpinel P&#233;rez
Jorge Orpinel P&#233;rez

Reputation: 6627

1-liner

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

// if( ! $end ) no match.

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

Upvotes: 0

someone
someone

Reputation: 1468

Another option:

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

Upvotes: 7

Related Questions