我尝试使用以下模式从youtube网址获取youtube ID.它似乎适用于普通的YouTube网址,
$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/
| /&v=/ # or ?feature=youtu.be&v=NXwxHU2Q0bo
| /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 ($result) {
return $matches[1];
}
Run Code Online (Sandbox Code Playgroud)
但是此网址失败了https://www.youtube.com/watch?feature=youtu.be&v=NXwxHU2Q0bo 和 https://m.youtube.com/watch?v=w7P_F7DGPU0
从上面的URL获取视频ID需要包含哪些模式?提前致谢
这是解决方案:
^# Match any youtube URL
(?:https?://)? # Optional scheme. Either http or https
(?:
www\. # Optional www subdomain
| m\. # Optional mobile subdomain
)?
(?: # Group host alternatives
youtu\.be/ # Either youtu.be,
| youtube\.com # or youtube.com
(?: # Group path alternatives
/ # Shortlink
| /embed/ # Either /embed/
| /v/ # or /v/
| /&v=/ # or ?feature=youtu.be&v=NXwxHU2Q0bo
| /watch\?v= # or /watch\?v=
| /watch\?feature=youtu\.be&v= # alternativ link with watch
) # End path alternatives.
) # End host alternatives.
([\w-]{10,12}) # Allow 10-12 for 11 char youtube id.
$
Run Code Online (Sandbox Code Playgroud)
https://regex101.com/r/LiCquP/2
https://regex101.com/r/LiCquP/3
为了测试:)
| 归档时间: |
|
| 查看次数: |
1430 次 |
| 最近记录: |