Preg_Match一个URL形式的字符串

时间:2009-07-14 14:21:08

标签: php regex string

我有一个URL作为字符串。如何匹配VideoID后面的数字。此外,VideoID可能出现在URL中的不同点。但之后我会担心,因为我甚至不能这样做。

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

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

print_r($matches);

......为一个菜鸟做一些改变。 :)

3 个答案:

答案 0 :(得分:3)

只需使用内置的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
)

答案 1 :(得分:1)

/(?:\?|&)VideoID=([0-9]+)/   # get just the ID, stored in \\1
/(?:\?|&)(VideoID=[0-9]+)/   # get VideoId=ID, stored in \\1

假设您的网址格式正确,它始终以?&开头,并且您的示例中的网址是严格的数字,因此它将匹配有效的ID到URL的下一部分。

答案 2 :(得分:0)

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