从 URL 正则表达式模式获取 YouTube ID [英] Get YouTube ID from URL regex pattern

查看:33
本文介绍了从 URL 正则表达式模式获取 YouTube ID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在网站上看到了几个不同的示例,但它没有从所有 youtube 选项中获取 id...作为示例,以下链接不适用于下面的正则表达式模式.任何帮助都会很棒.提前致谢:

I've seen a couple different examples on the site but it doesn't get the id out of all the youtube options... as an example the following links don't work with the regex pattern below. any help would be wonderful. Thanks in advance:

如果用户访问 youtube 主页并点击其中一个视频,他们会给出以下网址,这似乎就是这个:http://www.youtube.com/watch?v=hLSoU53DXK8&feature=g-vrec

It just seems to be this one if a user goes to youtube homepage and clicks on one of the vids there they give this url: http://www.youtube.com/watch?v=hLSoU53DXK8&feature=g-vrec

我的正则表达式将它放入数据库中为:hLSoU53DXK8-vrec,我需要它而不需要 -vrec.

my regex puts it in the database as: hLSoU53DXK8-vrec and i need it without -vrec.

// YOUTUBE
$youtube = $_POST['youtube'];


 function getYoutubeId($youtube) {
    $url = parse_url($youtube);
    if($url['host'] !== 'youtube.com' &&
             $url['host'] !== 'www.youtube.com'&&
             $url['host'] !== 'youtu.be'&&
             $url['host'] !== 'www.youtu.be')
        return false;
    $youtube = preg_replace('~
        # Match non-linked youtube URL in the wild. (Rev:20111012)
        https?://         # Required scheme. Either http or https.
        (?:[0-9A-Z-]+\.)? # Optional subdomain.
        (?:               # Group host alternatives.
          youtu\.be/      # Either youtu.be,
        | youtube\.com    # or youtube.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', 
        '$1',
        $youtube);
    return $youtube;
}

$youtube_id = getYoutubeId($youtube);

推荐答案

$url = "http://www.youtube.com/watch?v=hLSoU53DXK8&feature=g-vrec";
$query_string = array();

parse_str(parse_url($url, PHP_URL_QUERY), $query_string);

$id = $query_string["v"];

这篇关于从 URL 正则表达式模式获取 YouTube ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆