$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?
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 ...;
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With