grabbing variable...from inside a string

Ask about a PHP problem here.
Post Reply
Thunderbob
Posts: 46
Joined: Sat Jun 30, 2012 12:31 pm

grabbing variable...from inside a string

Post 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)
User avatar
Temor
Posts: 1186
Joined: Thu May 05, 2011 8:04 pm

Re: grabbing variable...from inside a string

Post by Temor »

So what you want is the actual video id?

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

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

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

echo $var2;[/syntax]

/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.
[syntax=php]<?php
$var = "http://www.youtube.com/watch?v=QktSpv6fOZ4&feature=g-list&list=PLd7ImvATttXJnIPaa_4u03AucpOmXccJP";

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

$var2 = $array[1];

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

echo $array2[0];[/syntax]

this will allow for any url input and will always pick the $_GET'['v'] variable.
Thunderbob
Posts: 46
Joined: Sat Jun 30, 2012 12:31 pm

Re: grabbing variable...from inside a string

Post by Thunderbob »

Thanks worked like a charm
User avatar
Temor
Posts: 1186
Joined: Thu May 05, 2011 8:04 pm

Re: grabbing variable...from inside a string

Post 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.
User avatar
Temor
Posts: 1186
Joined: Thu May 05, 2011 8:04 pm

Re: grabbing variable...from inside a string

Post 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.
Post Reply