使用正则表达式从 url 获取 id
http://example.com/movie.swf?url=http%3A%2F%2Fexample.com%2Fmovie%2F1234567
http://example.com/movie.swf?url=http%3A%2F%2Fexample.com%2Fmovie%2F1234567%2Fsubtitle
http://example.com/movie.swf?url=http%3A%2F%2Fexample.com%2Fmovie%2F123456
http://example.com/movie.swf?url=http%3A%2F%2Fexample.com%2Fmovie%2F123456%2Fsubtitle
http://example.com/movie.swf?url=http%3A%2F%2Fexample.com%2Fmovie%2F1234567%2F
http://example.com/movie.swf?url=http%3A%2F%2Fexample.com%2Fmovie%2F123456%2F
URL 始终以以下形式开头:
http://example.com/movie.swf?url=http%3A%2F%2Fexample.com%2Fmovie%2F
id 始终为数字,但位数可能会有所不同。
如何从上面的示例 URL 获取 id(1234567
和 123456
)?
我尝试使用以下模式但没有成功(它不返回任何匹配项):
/^http://example.com/movie.swf?url=http%3A%2F%2Fexample.com%2Fmovie%2F(\d)$/
http://example.com/movie.swf?url=http%3A%2F%2Fexample.com%2Fmovie%2F1234567
http://example.com/movie.swf?url=http%3A%2F%2Fexample.com%2Fmovie%2F1234567%2Fsubtitle
http://example.com/movie.swf?url=http%3A%2F%2Fexample.com%2Fmovie%2F123456
http://example.com/movie.swf?url=http%3A%2F%2Fexample.com%2Fmovie%2F123456%2Fsubtitle
http://example.com/movie.swf?url=http%3A%2F%2Fexample.com%2Fmovie%2F1234567%2F
http://example.com/movie.swf?url=http%3A%2F%2Fexample.com%2Fmovie%2F123456%2F
The URL's always start with:
http://example.com/movie.swf?url=http%3A%2F%2Fexample.com%2Fmovie%2F
The ids are always numeric, however the number of digits can vary.
How to get the id (1234567
and 123456
) from above sample URL's?
I've tried using the following pattern without luck (it doesn't return any matches):
/^http://example.com/movie.swf?url=http%3A%2F%2Fexample.com%2Fmovie%2F(\d)$/
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
我建议您首先解析此网址并提取
网址
查询字符串参数并对其进行 url 解码:如下所示:
然后使用一些正则表达式来解析
p
并提取必要的信息,例如/\d+/
。I would recommend you to first parse this url and extract the
url
query string parameter and url decoding it:like this:
and then use some regex to parse
p
and extract the necessary information like/\d+/
.使用正确的 URL 解析函数,您可以执行以下操作:
With proper URL parsing functions you can do this:
吻。我原本打算使用
parse_url()
,但无论如何都无法在没有正则表达式的情况下解析查询字符串。KISS. I was originally going to use
parse_url()
, but there is no way to parse a query string without regular expressions anyway.还有一种不解析的方法。假设 $url = URL
http://codepad.org/t91DK9H2
There's a way without parsing too. Assuming $url = URL
http://codepad.org/t91DK9H2
看来您需要转义一些特殊字符。
尝试:
/^http ://example.com/movie.swf\?url=http%3A%2F%2Fexample.com%2Fmovie%2F(\d+)$/
It looks likes you need to escape some special characters.
try:
/^http://example.com/movie.swf\?url=http%3A%2F%2Fexample.com%2Fmovie%2F(\d+)$/