简体   繁体   中英

Preg_Match a string in the form of a URL

I have a URL as a string. How do I match the numbers after the VideoID. Also VideoID may occur at different points in the URL. But I will worry about that afterwards, as I can't even do this.

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

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

print_r($matches);

...Spare some change for a noob. :)

Just use the built-in 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);

returns

 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

Under the assumption that your URL is properly formed, it will always be preceded by either ? or & , and with your example the URL is strictly numerical, so it will match a valid ID up to the next segment of the URL.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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