【问题标题】:Get YouTube video ID from URL w/ PHP使用 PHP 从 URL 获取 YouTube 视频 ID
【发布时间】:2011-11-05 11:53:01
【问题描述】:

我正在尝试创建一个函数,该函数从 Wordpress 自定义字段(YouTube 视频 URL 的“_videourl”)调用一个值,然后使用 PHP 修剪将其缩减为仅 YouTube 视频 ID。我找到了一个 javascript 函数,可以将 URL 缩减为仅 ID,但我不知道如何将其转换为 php(下面的函数):

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

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

编辑:已解决

经过一些实验,我找到了解决方案。我想返回并发布它,以便其他有需要的人可以从某个地方开始。

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;
        }

    } 

【问题讨论】:

标签: php regex wordpress function youtube


【解决方案1】:

我不得不为我几周前编写的一个 PHP 类处理这个问题,最终得到一个匹配任何类型字符串的正则表达式:有或没有 URL 方案,有或没有子域,youtube.com URL 字符串,youtu .be URL 字符串并处理各种参数排序。您可以查看at GitHub 或简单地复制并粘贴下面的代码块:

/**
 *  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;
}

为了解释正则表达式,这里有一个溢出版本:

/**
 *  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;
}

【讨论】:

  • 我可以确认这对我有用。很好的解决方案和解释!
【解决方案2】:

假设正则表达式是正确的,你可以使用preg_replace

$youtubeId = preg_replace('/^[^v]+v.(.{11}).*/', '$1', $url);

您可能还对str_replacesubstr 感兴趣。

【讨论】:

    【解决方案3】:

    我找到的最佳解决方案;

     function GetYouTubeId($url)
     {
     preg_match('%(?:youtube(?:-nocookie)?\.com/(?:[^/]+/.+/|(?:v|e(?:mbed)?)/|.*[?&]v=)|youtu\.be/)([^"&?/ ]{11})%i', $url, $match);
     $youtube_id = $match[1];
     return $youtube_id;
     }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-07-22
      • 2011-10-12
      • 2020-11-05
      • 2016-01-21
      • 2021-02-10
      • 2012-05-22
      • 2011-03-28
      相关资源
      最近更新 更多