问题描述
我只是想知道如何使用PHP提取URL的最后一部分.
I'm just wondering how I can extract the last part of a URL using PHP.
示例URL是:
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的最后一部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!