Hello Anders Falk here! I'm not so good with preg_match so this is why I have choose to create a thread here... Anyway I wonder how to just take out the video id from a youtube link? Only the video id. I got the site filmbladet.se and I really need help with this. So what can it be?... Some links looks like this and it's very annoying! http://www.youtube.com/watch?v=mgNmB...tra_param=true Other links have some sort of gdata_youtube behind.
I wouldn't use preg_match unless needed, this should be more handy: $var = parse_url('https://www.youtube.com/watch?v=oD26Mrf1mck&extra_param=test', PHP_URL_QUERY); parse_str($var, $var); echo $var['v']; PHP:
Okay... I've just got to ask - why does it HAVE to be preg_match? Why use a function with way more overhead for something so simple as this? parse_url is there for a reason, so... why preg_match?
Because I got an rss script that I post news from in filmbladet.se and those news youtube links be like youtube.com/watch?v=0iyeUcFKRv4=_g_data and more text... And the code can't embed if the link are like that. That's why we need to cut out the video id and cut in into the embed code!... And youtube.com/watch?v= will be there already!
Not sure if you've actually tried the code above, but it works just fine. It will just take the "v" variable from the URL and ignore the rest.
The v=CodeGoesHere need to separate the rest of the variables in the URL somehow, normally with an ampersand as separator - the parse_url-function uses this to only get the parameter you want, and discard the rest. Hence, no need for preg_match...
I wholefully recommend utilizing parse_url / parse_str as ThePHPMaster has exampled and only switch to the regular expression engine when absolutely needed, mainly due to overhead issues. That being said I've coded below the preg_match equivalent to parse_url / parse_str coded from ThePHPMaster and offer it here for educational purposes only since your wanting to learn more about preg_match and regex <?php $URI = 'http://www.youtube.com/watch?v=jNQXAC9IVRw&extra_param=foobar&more-foobar'; preg_match('/=(.*?)&/', $URI, $var); echo $var[1]; ?> PHP: noting the greedy-less lazy match (.*?) syntax to save literal traversing time and energy from the regex parser and using it between first equals sign and ampersand in the URI. .