0

In the messages users write with eachother, I wish to turn Youtube links into the youtube thumbnail of it+title.

So how can I check if $msg contains a youtube video link, and if it does, it should take the video id (?v=) of it, and run this:

$.getScript( 'http://gdata.youtube.com/feeds/api/videos/$videoid?v=2&alt=json-in-script&callback=youtubeFetchDataCallback' );

How can this be done?

Johnson
  • 818
  • 4
  • 21
  • 39

1 Answers1

1

Already resolved partially here: parse youtube video id using preg_match

EDIT alternatively you could use parse_url() in PHP check the host is youtube and if it is read the query string and split into key/value pairs and read the "v" value

EDIT 2

<?php
$url = "http://www.youtube.com/watch?v=QDe6MZQjpho";
$url = parse_url($url);
if($url['host'] == "www.youtube.com") {
    parse_str($url['query'], $output);
    $videoID = $output['v'];
} else {
    echo "not youtube.com";
}
?>

EDIT 3 Another way

<?php
$url = "http://www.youtube.com/watch?v=QDe6MZQjpho";
if(preg_match("#http://(.*)\.youtube\.com/watch\?v=(.*)(&(.*))?#", $url, $matches)){
    $videoID = $matches[2];
} else {
    echo "not youtube.com";
}
?>
Community
  • 1
  • 1
Scott
  • 3,967
  • 9
  • 38
  • 56
  • The link you provided wont support urls like: &hl=en_GB&fs=1... And how can I make a if statement if it contains the preg_match? – Johnson Nov 09 '10 at 16:05
  • Just ran it, it gave me "no youtube". And it should be watch?v=... but still it doesn't work – Johnson Nov 09 '10 at 16:17
  • ok put in a youtube url you know is correct into the $url variable. you might need to add www. to the if statement. Also if your checking .co.uk and other domains you will need to add || to the if statement to capture them too. – Scott Nov 09 '10 at 16:22
  • I believe there exist a better solution that doing that, e.g regex that supports all this + strips the stuff after watch?v=.... (such as &hl=en, &related ...) – Johnson Nov 09 '10 at 16:27
  • parse_url($url) breaks the url down to its key components. All you need to do is find a better way for checking the host value is youtube.com. if you know its the correct host then parse_str is the best way to get the values of the URL. Looks like you are only after the "v" variable anyway. It doesnt matter if the URL has other values on the end it wont effect the matching of the host. – Scott Nov 09 '10 at 16:33