繁体   English   中英

Preg_Match一个URL形式的字符串

[英]Preg_Match a string in the form of a URL

我有一个URL作为字符串。 如何在VideoID之后匹配数字。 VideoID也可能出现在URL中的不同位置。 但是我以后会担心,因为我什至无法做到这一点。

$string = 'http://example.com/index.php?action=vids.individual&VideoID=60085484';

preg_match('/(?<VideoID>)=/', $string, $matches);

print_r($matches);

...为菜鸟保留一些零钱。 :)

只需使用内置的parse_url / parse_str

$string = 'http://example.com/index.php?action=vids.individual&VideoID=60085484';
$URL = parse_url($string);
parse_str($URL['query'],$Q);
print_r($Q);

回报

 Array ( [action] => vids.individual [VideoID] => 60085484 ) 
/(?:\?|&)VideoID=([0-9]+)/   # get just the ID, stored in \\1
/(?:\?|&)(VideoID=[0-9]+)/   # get VideoId=ID, stored in \\1

在假定您的URL格式正确的前提下,始终以?开头? & ,并且在您的示例中,URL是严格数字的,因此它将与有效ID匹配,直到URL的下一段。

$string = 'http://example.com/index.php?action=vids.individual&VideoID=60085484&somethingelse';
$s = explode("VideoID=",$string);
print preg_replace("/[^0-9].*/","",$s[1]);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM