I have a PHP variable that contains one of two possible kind of URL:
$text = "http://www.youtube.com/v/wUJQPbALd68?version=3&autohide=1&autoplay=1";
$text = " http://www.youtube.com/watch?v=IcrbM1l_BoI
How can I extract the id from the url for the two type? I think I have to use regex but I am a very newbie.
For example in first $text
is wUJQPbALd68
and in the second is IcrbM1l_BoI
.
Thanks a lot.
/**
* get youtube video ID from URL
*
* @param string $url
* @return string Youtube video id or FALSE if none found.
* @authro hakre
*/
function youtube_id_from_url($url) {
$pattern =
'%^# Match any youtube URL
(?:https?://)? # Optional scheme. Either http or https
(?:www\.)? # Optional www subdomain
(?: # Group host alternatives
youtu\.be/ # Either youtu.be,
| youtube\.com # or youtube.com
(?: # Group path alternatives
/embed/ # Either /embed/
| /v/ # or /v/
| /watch\?v= # or /watch\?v=
) # End path alternatives.
) # End host alternatives.
([\w-]{10,12}) # Allow 10-12 for 11 char youtube id.
$%x'
;
$result = preg_match($pattern, $url, $matches);
if (false !== $result) {
return $matches[1];
}
return false;
}
Youtube API - Extract video ID
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