Mia
Mia

Reputation: 143

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. :)

Upvotes: 0

Views: 1288

Answers (3)

Eddy
Eddy

Reputation: 1862

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
)

Upvotes: 3

ghostdog74
ghostdog74

Reputation: 342313

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

Upvotes: 0

Ian Elliott
Ian Elliott

Reputation: 7686

/(?:\?|&)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.

Upvotes: 1

Related Questions