Reputation: 3223
I'm trying to grab parts of a URL to create an embed code. I have the following URL structure:
http://www.mtv.com/videos/foster-the-people/761507/houdini.jhtml#id=1518072&vid=761507
I need to use preg_match
to break the URL into a few pieces. Ideally, I want to test for the structure of the URL and get the numeric values from the URL. Ultimately, I would like an array in the following form after the preg_match
:
Array (
0 => 761507
1 => 1518072
2 => 761507
)
Note that "foster-the-people" and "houdini" are dynamic elements that can contain letters, numbers and "-" and will change from URL to URL.
Thanks for the help!
Upvotes: 1
Views: 2835
Reputation: 784988
I would suggest you to use parse_url first to break your URL into individual components and then if needed use preg_match to get individual sub-items from $urlarr['query']
where $urlarr
is return value of parse_url.
Upvotes: 0
Reputation: 22810
Try this : (UPDATED)
http:\/\/www\.mtv\.com\/videos\/.*?\/([0-9]+)\/.*?id=([0-9]+)&vid=([0-9]+)
Demo :
Code :
<?php
$subject = "http://www.mtv.com/videos/foster-the-people/761507/houdini.jhtml#id=1518072&vid=761507";
$pattern = '/http:\/\/www\.mtv\.com\/videos\/.*?\/([0-9]+)\/.*?id=([0-9]+)&vid=([0-9]+)/';
preg_match($pattern, $subject, $matches);
print_r($matches);
?>
Output :
Array
(
[0] => http://www.mtv.com/videos/foster-the-people/761507/houdini.jhtml#id=1518072&vid=761507
[1] => 761507
[2] => 1518072
[3] => 761507
)
Hint : The elements you need are $matches[1]
, $matches[2]
and $matches[3]
Upvotes: 2