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.
One line working answer:
$url = "http://www.yoursite/one/two/three/drink";
echo $end = end((explode('/', $url)));
Output: drink
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.
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.
$mylink = $_SERVER['PHP_SELF'];
$link_array = explode('/',$mylink);
echo $lastpart = end($link_array);
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
1-liner
$end = preg_replace( '%^(.+)/%', '', $url );
// if( ! $end ) no match.
This simply removes everything before the last slash, including it.
Another option:
$urlarray=explode("/",$url);
$end=$urlarray[count($urlarray)-1];
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.
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.
One liner: $page_path = end(explode('/', trim($_SERVER['REQUEST_URI'], '/')));
Get URI, trim slashes, convert to array, grab last part
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));
$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!
Source: Stackoverflow.com