获取 URL 的最后一部分 PHP
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7395049/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get Last Part of URL PHP
提问by Belgin Fish
I'm just wondering how I can extract the last part of a URL using PHP.
我只是想知道如何使用 PHP 提取 URL 的最后一部分。
The example URL is:
示例网址是:
http://domain.com/artist/song/music-videos/song-title/9393903
Now how can I extract the final part using PHP?
现在如何使用 PHP 提取最后一部分?
9393903
There is always the same number of variables in the URL, and the id is always at the end.
URL中总是有相同数量的变量,id总是在最后。
采纳答案by Belgin Fish
You can use preg_match
to match the part of the URL that you want.
您可以使用preg_match
来匹配所需的 URL 部分。
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)).
在这种情况下,由于模式很简单,我们正在寻找一个正斜杠(\/
我们必须转义它,因为正斜杠表示正则表达式模式的开始和结束),以及一个或多个数字 ( \d+
) 在字符串的末尾 ( $
)。周围的括号\d+
用于捕获我们想要的片段:即结尾。然后我们将我们想要的结尾 ( $end
)分配给$matches[1]
(不是$matches[0]
,因为它与$url
(即整个字符串)相同)。
$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 alwaysstart with http://
then the regex can become /^http:\/\/.*\/(\d+)$/
(where .*
means zero or more characters (that aren't the newline character)).
注意:您可能想也可能不想为这个正则表达式添加一些更复杂的东西。例如,如果您知道您的 URL 字符串总是以开头,http://
那么正则表达式可以变成/^http:\/\/.*\/(\d+)$/
(其中.*
表示零个或多个字符(不是换行符))。
回答by nikc.org
The absolute simplest way to accomplish this, is with basename()
实现这一点的最简单的方法是 basename()
echo basename('http://domain.com/artist/song/music-videos/song-title/9393903');
Which will print
哪个会打印
9393903
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.
当然,如果末尾有查询字符串,它将包含在返回值中,在这种情况下,接受的答案是更好的解决方案。
回答by hakre
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:
编辑:要支持 apache 风格的规范 URL,rtrim
很方便:
$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):
我认为更具可读性的另一个示例是(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.
这个例子还考虑到只对 URL 的路径起作用。
Yet another edit(years after), canonicalization and easy UTF-8 alternative use included (via PCRE regular expression in PHP):
另一个编辑(多年后),包括规范化和简单的 UTF-8 替代使用(通过 PHP 中的 PCRE 正则表达式):
<?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.
这很粗糙,但展示了如何preg_match
通过 PCRE 正则表达式模式将其包装在更细粒度控制的调用中。为了给这个裸机示例添加一些意义,它应该包含在它自己的函数中(这也会使混叠变得多余)。为简洁起见,仅以这种方式呈现。
回答by Peter
回答by Tamer Shlash
$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
这里是strrchr
函数的描述:http: //www.php.net/manual/en/function.strrchr.php
Hope that's useful!
希望有用!
回答by someone
Another option:
另外一个选项:
$urlarray=explode("/",$url);
$end=$urlarray[count($urlarray)-1];
回答by Justin
One liner: $page_path = end(explode('/', trim($_SERVER['REQUEST_URI'], '/')));
一个班轮: $page_path = end(explode('/', trim($_SERVER['REQUEST_URI'], '/')));
Get URI, trim slashes, convert to array, grab last part
获取 URI,修剪斜线,转换为数组,获取最后一部分
回答by Robert Sinclair
One of the most elegant solutions was here Get characters after last / in url
最优雅的解决方案之一是Get characters after last / in url
by DisgruntledGoat
by 心怀不满的山羊
$id = substr($url, strrpos($url, '/') + 1);
strrpos gets the position of the last occurrence of the slash; substr returns everything after that position.
strrpos 获取最后一次出现斜杠的位置;substr 返回该位置之后的所有内容。
回答by XxANxX
this will do the job easily to get the last part of the required URL
这将轻松完成工作以获取所需 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.
这将为您提供右侧第一个“/”之后的字符串。
回答by Jorge Orpinel
1-liner
1-班轮
$end = preg_replace( '%^(.+)/%', '', $url );
// if( ! $end ) no match.
This simply removes everything before the last slash, including it.
这只是删除最后一个斜杠之前的所有内容,包括它。