我有一个PHP变量,它包含两种可能的URL之一:
$text = "http://www.youtube.com/v/wUJQPbALd68?version=3&autohide=1&autoplay=1";
$text = " http://www.youtube.com/watch?v=IcrbM1l_BoI
Run Code Online (Sandbox Code Playgroud)
如何从两个类型的URL中提取id?我想我必须使用正则表达式,但我是一个非常新手.
例如,在第一$text是wUJQPbALd68和在第二个是IcrbM1l_BoI.
非常感谢.
/**
* 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;
}
Run Code Online (Sandbox Code Playgroud)