YouTube视频网址可能会以多种格式出现:
这是带有带注释的正则表达式的PHP函数,该函数与这些URL形式中的每一个匹配,并将它们转换为链接(如果它们还不是链接):
// Linkify youtube URLs which are not already links.
function linkifyYouTubeURLs($text) {
$text = preg_replace('~(?#!js YouTubeId Rev:20160125_1800)
# Match non-linked youtube URL in the wild. (Rev:20130823)
https?:// # required scheme. Either http or https.
(?:[0-9A-Z-]+\.)? # Optional subdomain.
(?: # Group host alternatives.
youtu\.be/ # Either youtu.be,
| youtube # or youtube.com or
(?:-nocookie)? # youtube-nocookie.com
\.com # followed by
\S*? # Allow anything up to VIDEO_ID,
[^\w\s-] # but char before ID is non-ID char.
) # End host alternatives.
([\w-]{11}) # $1: VIDEO_ID is exactly 11 chars.
(?=[^\w-]|$) # Assert next char is non-ID or EOS.
(?! # Assert URL is not pre-linked.
[?=&+%\w.-]* # Allow URL (query) remainder.
(?: # Group pre-linked alternatives.
[\'"][^<>]*> # Either inside a start tag,
| </a> # or inside <a> element text contents.
) # End recognized pre-linked alts.
) # End negative lookahead assertion.
[?=&+%\w.-]* # Consume any URL (query) remainder.
~ix', '<a href="http://www.youtube.com/watch?v=$1">YouTube link: $1</a>',
$text);
return $text;
}
; //结束$ YouTubeId。
这是具有完全相同的正则表达式的JavaScript版本(已删除注释):
// Linkify youtube URLs which are not already links.
function linkifyYouTubeURLs(text) {
var re = /https?:\/\/(?:[0-9A-Z-]+\.)?(?:youtu\.be\/|youtube(?:-nocookie)?\.com\S*?[^\w\s-])([\w-]{11})(?=[^\w-]|$)(?![?=&+%\w.-]*(?:['"][^<>]*>|<\/a>))[?=&+%\w.-]*/ig;
return text.replace(re,
'<a href="http://www.youtube.com/watch?v=$1">YouTube link: $1</a>');
}
-
在ID字符类中添加了连字符
修复了正则表达式以使用YouTube ID后占用URL的任何其余部分(例如 query )的问题。添加了'i'
忽略大小写 修饰符。将函数重命名为camelCase。改进的预链接超前测试。
添加了YouTube URL的新“用户”和“ ytscreeningroom”格式。
简化/通用化以处理新的“任意/全部/正常” YouTube URL。
一些修改:
YouTube URL主机部分现在可以具有任何子域(而不仅仅是www.
)。
消费URL部分现在可以使用’-‘。
添加了@CRONUS提供的其他格式:youtube-nocookie.com
。
2016年1月25日 修复了正则表达式以处理CRONUS提供的错误情况。