获取 URL 的最后部分

我只是想知道如何使用 PHP 提取 URL 的最后一部分。

示例 URL 是:

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

现在我如何使用 PHP 提取最后一部分?

9393903

URL 中总是有相同数量的变量,并且 id 总是在最后。

138504 次浏览

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

$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

Another option:

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

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.

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.

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));

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.

1-liner

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


// if( ! $end ) no match.

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

One line working answer:

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

Output: drink

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

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

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

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.

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
function getLastPathSegment($url) {
$arr = explode('/', $url);
return $arr[count($arr) - 1];
}