您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

如何使用正则表达式查找字符串中的所有YouTube视频ID?

如何使用正则表达式查找字符串中的所有YouTube视频ID?

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部分现在可以使用’-‘。

添加了@Mei提供的其他格式。(查询部分可能有一个.点。

添加了@CRONUS提供的其他格式:youtube-nocookie.com

2016年1月25日 修复了正则表达式以处理CRONUS提供的错误情况。

其他 2022/1/1 18:20:53 有226人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶