从w / PHP网址获取YouTube视频ID [英] Get YouTube video ID from URL w/ PHP

查看:263
本文介绍了从w / PHP网址获取YouTube视频ID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试创建一个函数,用于调用WordPress自定义字段中的值(_videourl代表YouTube视频网址),然后使用PHP剪裁将其剪裁为YouTube视频ID。我发现了一个JavaScript功能,可以将URL简化为ID,但我不知道如何将它翻译成php(下面的函数):

 函数youtubeIDextract(url)
{
var youtube_id;
youtube_id = url.replace(/ ^ [^ v] + v。(。{11})。* /,$ 1);
返回youtube_id;
}

这个PHP函数会在循环中使用,所以我认为我将不得不使用变量,但我真的只是一个noob,所以我不知道该怎么做。任何人都可以通过分享他们的编码专业知识来帮助我创建一个PHP函数吗?

编辑:已解决

经过一些实验后,我找到了一个解决方案。

 函数getYoutubeId($ ytURL)返回并发布它,以便其他需要的人也可以从某处开始。 
{
$ urlData = parse_url($ ytURL);
// echo'< br>'。$ urlData [host]。'< br>';
if($ urlData [host] =='www.youtube.com')//检查有效的YouTube网址
{
$ ytvIDlen = 11; //这是YouTube视频ID的长度

// ID字符串在v =之后开始,通常在
//youtube.com/watch?之后。在URL
$ idStarts = strpos($ ytURL,?v =);

//如果v =不在?之后(不太可能,但我想保留我的
//基数),它会在&之后:
if($ idStarts === FALSE)
$ idStarts = strpos($ ytURL,& v =);
//如果仍然为FALSE,则URL没有vid ID
if($ idStarts === FALSE)
die(未找到YouTube视频ID,请仔细检查您的网址。);

//抵消起始位置以匹配ID字符串的开始处
$ idStarts + = 3;

//获取ID字符串并返回它
$ ytvID = substr($ ytURL,$ idStarts,$ ytvIDlen);

返回$ ytvID;
}
else
{
// echo'这不是有效的youtube视频网址。请给出一个有效的网址...';
返回0;
}

}


解决方案

我必须为几个星期前写的PHP类处理这个问题,最后得到一个匹配任何类型字符串的正则表达式:带或不带URL的方案,带或不带子域,youtube.com URL字符串,youtu 。URL字符串和处理所有类型的参数排序。您可以在GitHub上查看或只需复制并粘贴以下代码块:

  / ** 
*检查输入字符串是否为有效的YouTube URL
*并尝试从中提取YouTube视频ID。
* @author Stephan Schmitz< eyecatchup@gmail.com>
* @param $ url字符串应检查的字符串。
* @return mixed返回YouTube视频ID,或(布尔)false。
* /
function parse_yturl($ url)
{
$ pattern ='#^(?:https?://)?(?:www \。)? (:????。youtu\.be / | youtube\.com(:/嵌入/ | / v / | / watch\ v = | / watch\ +安培; v =))([\\ \\w - ] {11})(?:?+)$#X';
preg_match($ pattern,$ url,$ matches);
return(isset($ matches [1]))? $ matches [1]:false;
}

解释正则表达式,这是一个溢出版本:

  / ** 
*检查输入的字符串是否为有效的YouTube网址
*,并尝试从中提取YouTube视频ID它。
* @author Stephan Schmitz< eyecatchup@gmail.com>
* @param $ url字符串应检查的字符串。
* @return mixed返回YouTube视频ID,或(布尔)false。
* /
function parse_yturl($ url)
{
$ pattern ='#^(?:https?://)?'; #可选的URL方案。 http或https。
$ pattern。='(?:www \。)?'; #可选的www子域。
$ pattern。='(?:';#分组主机替代:
$ pattern。='youtu\.be /';#youtu.be,
$ pattern。= '| youtube\.com';#或youtube.com
$ pattern。='(?:';#Group path alternatives:
$ pattern。='/ embed /';#或者/ embed /,
$ pattern。='| / v /';#or / v /,
$ pattern。='| / watch\?v =';#or / watch?v = ,
$ pattern。='| / watch\?。+& v =';#或/ watch?other_param& v =
$ pattern。=')';#结束路径选择。
$ pattern。=')'; #结束主机替代。
$ pattern。='([\w - ] {11})'; #11个字符(Youtube视频ID的长度)。
$ pattern。='(?:。+)?$#x'; #可选的其他结束URL参数。
preg_match($ pattern,$ url,$ matches);
return(isset($ matches [1]))? $ matches [1]:false;
}


I'm trying to create a function that calls a value from a Wordpress custom field ("_videourl" for a YouTube video URL) and then uses PHP trim to cut it down to just the YouTube video ID. I found a javascript function that cuts down URLs to just the ID but I have no idea how I'd be able to translate that into php (function below):

     function youtubeIDextract(url) 
     { 
     var youtube_id; 
     youtube_id = url.replace(/^[^v]+v.(.{11}).*/,"$1"); 
     return youtube_id; 
     }

This PHP function would be used inside the loop so I think I would have to use variables, but I'm really just a noob so I have no idea what to do. Can anyone help by sharing their coding expertise in helping me create a PHP function?

EDIT:SOLVED

After some experimentation, I found a solution. I wanted to return and post it so that others also in need would have somewhere to start from.

function getYoutubeId($ytURL) 
    {
        $urlData = parse_url($ytURL);
        //echo '<br>'.$urlData["host"].'<br>';
        if($urlData["host"] == 'www.youtube.com') // Check for valid youtube url
        {
            $ytvIDlen = 11; // This is the length of YouTube's video IDs

            // The ID string starts after "v=", which is usually right after 
            // "youtube.com/watch?" in the URL
            $idStarts = strpos($ytURL, "?v=");

            // In case the "v=" is NOT right after the "?" (not likely, but I like to keep my 
            // bases covered), it will be after an "&":
            if($idStarts === FALSE)
                $idStarts = strpos($ytURL, "&v=");
            // If still FALSE, URL doesn't have a vid ID
            if($idStarts === FALSE)
                die("YouTube video ID not found. Please double-check your URL.");

            // Offset the start location to match the beginning of the ID string
            $idStarts +=3;

            // Get the ID string and return it
            $ytvID = substr($ytURL, $idStarts, $ytvIDlen);

            return $ytvID;
        }
        else
        {
            //echo 'This is not a valid youtube video url. Please, give a valid url...';
            return 0;
        }

    } 

解决方案

I had to deal with this for a PHP class i wrote a few weeks ago and ended up with a regex that matches any kind of strings: With or without URL scheme, with or without subdomain, youtube.com URL strings, youtu.be URL strings and dealing with all kind of parameter sorting. You can check it out at GitHub or simply copy and paste the code block below:

/**
 *  Check if input string is a valid YouTube URL
 *  and try to extract the YouTube Video ID from it.
 *  @author  Stephan Schmitz <eyecatchup@gmail.com>
 *  @param   $url   string   The string that shall be checked.
 *  @return  mixed           Returns YouTube Video ID, or (boolean) false.
 */        
function parse_yturl($url) 
{
    $pattern = '#^(?:https?://)?(?:www\.)?(?:youtu\.be/|youtube\.com(?:/embed/|/v/|/watch\?v=|/watch\?.+&v=))([\w-]{11})(?:.+)?$#x';
    preg_match($pattern, $url, $matches);
    return (isset($matches[1])) ? $matches[1] : false;
}

To explain the regex, here's a spilt up version:

/**
 *  Check if input string is a valid YouTube URL
 *  and try to extract the YouTube Video ID from it.
 *  @author  Stephan Schmitz <eyecatchup@gmail.com>
 *  @param   $url   string   The string that shall be checked.
 *  @return  mixed           Returns YouTube Video ID, or (boolean) false.
 */        
function parse_yturl($url) 
{
    $pattern = '#^(?:https?://)?';    # Optional URL scheme. Either http or https.
    $pattern .= '(?:www\.)?';         #  Optional www subdomain.
    $pattern .= '(?:';                #  Group host alternatives:
    $pattern .=   'youtu\.be/';       #    Either youtu.be,
    $pattern .=   '|youtube\.com';    #    or youtube.com
    $pattern .=   '(?:';              #    Group path alternatives:
    $pattern .=     '/embed/';        #      Either /embed/,
    $pattern .=     '|/v/';           #      or /v/,
    $pattern .=     '|/watch\?v=';    #      or /watch?v=,    
    $pattern .=     '|/watch\?.+&v='; #      or /watch?other_param&v=
    $pattern .=   ')';                #    End path alternatives.
    $pattern .= ')';                  #  End host alternatives.
    $pattern .= '([\w-]{11})';        # 11 characters (Length of Youtube video ids).
    $pattern .= '(?:.+)?$#x';         # Optional other ending URL parameters.
    preg_match($pattern, $url, $matches);
    return (isset($matches[1])) ? $matches[1] : false;
}

这篇关于从w / PHP网址获取YouTube视频ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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