Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parsing Youtube links automatically

Tags:

php

youtube

$message = preg_replace("#(http://(www.)?youtube.com)?/(v/|watch\?v\=)([-|~_0-9A-Za-z]+)&?.*?#i", "<iframe title=\"YouTube\" width=\"480\" height=\"390\" src=\"http://www.youtube.com/embed/$4\" frameborder=\"0\" allowfullscreen></iframe>", $message);

This works fine if youtube link looks like this:

http://www.youtube.com/watch?v=9DhSwsbKJQ4

but there is a problem if Youtube link looks like this:

http://www.youtube.com/watch?v=9DhSwsbKJQ4&feature=topvideos_music

The result is iframe and text feature=topvideos_music after iframe. Is there any way how to remove everything after & in Youtube link?

like image 515
tfe Avatar asked Jun 07 '11 14:06

tfe


2 Answers

Why won't you use parse_url() and parse_str() functions? It's a much safer solution.

$url = 'http://www.youtube.com/watch?v=9DhSwsbKJQ4&feature=topvideos_music';
// $url = 'http://www.youtube.com/v/9DhSwsbKJQ4?feature=topvideos_music';

$parsedUrl = parse_url($url);
parse_str($parsedUrl['query'], $parsedQueryString);

// URL in ?v=... form
if (isset($parsedQueryString['v'])) {
    $id = $parsedQueryString['v'];
}
// URL in /v/... form
else if (substr($parsedUrl['path'], 0, 3) == '/v/') {
    $id = substr($parsedUrl['path'], 3);
}
// invalid form
else {
    throw new ...;
}
like image 158
Crozin Avatar answered Oct 13 '22 01:10

Crozin


You'd be better off decomposing the URL with parse_url()/parse_str(), then rebuilding it from the ground up.

$url = 'http://www.youtube.com/....';

$url_parts = parse_url($url);

$query_parts = parse_str($parts['query']);

$v = $query_parts['v'];

$new_url = $url_parts['scheme']; // http
$new_url .= '://';
$new_url .= $url_parts['host']; // www.youtube.com
$new_url .= '/';
$new_url .= $url_parts['path']; // /
$new_url .= '?'
$new_url .= 'v' . $v; // v=....

While parseing with regex will work, at some point it'll turn around and bite you. This is a bit more tedious, but safer in the long run.

like image 24
Marc B Avatar answered Oct 12 '22 23:10

Marc B