Page 1 of 1

grabbing variable...from inside a string

Posted: Mon Mar 18, 2013 4:21 pm
by Thunderbob
Hello

So I want to make it very easy for site visitors to share videos that they find on youtube.
At first I was requiring them to copy and paste the embed code and the video url(for like buttons)
I feel that it's a little to much for them and most of the time they mess up.

Now I want to store only the url but the most important aspect of the url is the variable "v".

Example: http://www.youtube.com/watch?v=ccT8C2wSC6Y

The important piece is ?v=ccT8C2wSC6Y
unfortunately when that variable is stored inside the database I don't know how to grab the ?v=ccT8C2wSC6Y
part which is needed for thumbnails.

My question is... how can I store the video url http://www.youtube.com/watch?v=ccT8C2wSC6Y inside the database
and later grab the ?v=ccT8C2wSC6Y part only.

(just entering in ?v=ccT8C2wSC6Y is not a solution for other reasons)

Re: grabbing variable...from inside a string

Posted: Mon Mar 18, 2013 4:49 pm
by Temor
So what you want is the actual video id?

if so, here's my solution:
<?php
$var = "http://www.youtube.com/watch?v=ccT8C2wSC6Y";

$array = explode("?",$var);

$var2 = substr($array[1], 2);

echo $var2;
/Edit; This will obviously only work if the input string always looks the same. If your users copy and paste a link from a playlist or anything else that changes the URL you would need to disallow that.


/Edit2; I did some more thinking and this is what I came up with.
<?php
$var = "http://www.youtube.com/watch?v=QktSpv6f ... ucpOmXccJP";

$array = explode("v=",$var);

$var2 = $array[1];

$array2 = explode("&",$var2);

echo $array2[0];
this will allow for any url input and will always pick the $_GET'['v'] variable.

Re: grabbing variable...from inside a string

Posted: Tue Mar 19, 2013 7:46 pm
by Thunderbob
Thanks worked like a charm

Re: grabbing variable...from inside a string

Posted: Tue Mar 19, 2013 9:26 pm
by Temor
There are better ways of doing this.
I'm guessing you could use regex to do this too, but my belief is that regex syntax is the devil, so I haven't bothered learning it.

Re: grabbing variable...from inside a string

Posted: Tue Mar 19, 2013 9:26 pm
by Temor
There are better ways of doing this.
I'm guessing you could use regex to do this too, but my belief is that regex syntax is the devil, so I haven't bothered learning it.