Save youtube video url to database

Hello,
I want to save url of youtube video into my database and later show on my website. Currently I have form where I’m able to save in DB but I have two problems/questions.

  1. How can I save only this v=7r7r_qU8Eow for example and not whole URL. My point is that I can’t force users to extract just this ‘v=7r7r_qU8Eow’ from whole URL. And if user enter this - “https://www.youtube.com/watch?v=7r7r_qU8Eow” in DB must save only ‘v=7r7r_qU8Eow’.
  2. How exactly to retrieve from DB video and show on website?

I have tryed with embeded code but no success. I’ve tryed like this:

$outputList .= "<iframe width=\\"640\\" height=\\"360\\" src=\\"http://www.youtube.com/embed/<?php echo $row[video_url]; ?>\\" frameborder=\\"0\\" allowfullscreen></iframe><br /><br />";

Ok, I’ve made it something that works but I don’t know if is good solution?
When I upload URL of video:

$video_url = $_POST['video_url'];
    $video_url = explode('=', $video_url);
    $video_url = $video_url['1'];

and when I show it on the site I use it like this

<iframe width=\\"640\\" height=\\"360\\" src=\\"https://www.youtube.com/embed/$video_url\\" frameborder=\\"0\\" allowfullscreen></iframe>

You can do it with javascript:



var video_id = window.location.search.split('v=')[1];
var ampersandPosition = video_id.indexOf('&');
if(ampersandPosition != -1) {
 video_id = video_id.substring(0, ampersandPosition);



Hope it helps.

Yes, this version helps also but I realize that I have another problem. What if the URL is longer and from playlist… Like this one

Here will save after first ‘=’ … only this ‘dCVDQqf4ouA’.

To alter my previous post, you could use a Regular Expression to go along with this Regular Expression:


var link = 'https://www.youtube.com/watch?v=hv_X327YUdI&list=SPGznEl712WelO6ZhS8lc2ssweLuQaCKld';
var reg = new RegExp("[&?]list=([a-z0-9_]+)","i");



It’s abridged but you get the idea. If you want to use both approaches it’s cool. Or, you could just use a regex for both of them to keep your code clean. It’s an OCD thing :wink:

Thank’s for your help. I will try to make it.
Regards!