获取 URL 的最后一部分 PHP [英] Get Last Part of URL PHP

查看:58
本文介绍了获取 URL 的最后一部分 PHP的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

示例网址为:

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

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

Now how can I extract the final part using PHP?

9393903

URL 中总是有相同数量的变量,并且 id 总是在末尾.

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

推荐答案

您可以使用 preg_match 匹配您想要的 URL 部分.

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

在这种情况下,由于模式很简单,我们正在寻找一个正斜杠(/,我们必须转义它,因为正斜杠表示正则表达式的开头和结尾模式),以及在字符串最末尾的一位或多位数字 (d+) ($).d+ 周围的括号用于捕获我们想要的部分:即结尾.然后我们将我们想要的结尾 ($end) 分配给 $matches[1](不是 $matches[0],因为那是与 $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)).

$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.
}

注意:您可能希望也可能不想为此正则表达式添加一些更复杂的内容.例如,如果您知道您的 URL 字符串总是http:// 开头,那么正则表达式可以变成 /^http://.*/(d+)$/ (其中 .* 表示零个或多个字符(不是换行符)).

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

这篇关于获取 URL 的最后一部分 PHP的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆