【问题标题】:parse youtube video id using preg_match [duplicate]使用 preg_match 解析 youtube 视频 ID [重复]
【发布时间】:2011-02-25 13:26:30
【问题描述】:

我正在尝试使用 preg_match 解析 youtube URL 的视频 ID。我在这个网站上发现了一个似乎有效的正则表达式;

(?<=v=)[a-zA-Z0-9-]+(?=&)|(?<=[0-9]/)[^&\n]+|(?<=v=)[^&\n]+

如图所示:

我的PHP如下,但是不起作用(给出未知修饰符'['错误)...

<?
 $subject = "http://www.youtube.com/watch?v=z_AbfPXTKms&NR=1";

 preg_match("(?<=v=)[a-zA-Z0-9-]+(?=&)|(?<=[0-9]/)[^&\n]+|(?<=v=)[^&\n]+", $subject, $matches);

 print "<pre>";
 print_r($matches);
 print "</pre>";

?>

干杯

【问题讨论】:

  • 在您的 RegexBuddy 中,您选择了 Java 作为语言。还有一个“使用”选项卡,您可以单击该选项卡,该选项卡将为您提供正确转义的代码,以用于多种不同的情况。
  • 因为其他问题有最佳答案,很好解释。
  • @Toto 如果您看到最新的 cmets,它在某些情况下也无法匹配 - 所以并不是更好的答案

标签: php regex parsing youtube


【解决方案1】:

这个正则表达式从我能找到的所有各种 URL 中获取 ID... 那里可能还有更多,但我在任何地方都找不到它们的参考。如果你遇到一个不匹配的,请在 URL 中留下评论,我会尝试更新正则表达式以匹配你的 URL。

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

以下是此正则表达式匹配的 URL 示例:(在给定 URL 之后可能有更多内容将被忽略)

它也适用于具有上述相同选项的 youtube-nocookie.com URL。

它还会在嵌入代码(iframe 和对象标签)中从 URL 中提取 ID

【讨论】:

  • 我正在使用上面提供的表达式,并且总是在视频 ID 中获得结尾 /iframe>。
  • 你能给出一个 pastebin 例子的链接吗?或者在这里创建一个关于 SO 的问题并在此处链接到它?
  • 再次...您有代码示例吗?你使用正确吗?我刚刚用你的 URL 测试了它,它返回了一个数组,在 $match[1] 中是 '9ofSV-ATEB0',它是 id。
  • @Benjam 你有一个像这样的 vimeo 的 preg_match 吗!这是一个很棒的 regX +1。谢谢!
  • 在移动用户名/...检查时,/?v=iframe/object 变体获得了更好的结果 (@987654334 @) 到后面:%(?:youtube(?:-nocookie)?\.com/(?:(?:v|e(?:mbed)?)/|.*[?&amp;]v=|[^/]+/.+/)|youtu\.be/)([^"&amp;?/ ]{11})%i。对于其他变体,它保持不变。
【解决方案2】:

最好使用parse_urlparse_str来解析URL和查询字符串:

$subject = "http://www.youtube.com/watch?v=z_AbfPXTKms&NR=1";
$url = parse_url($subject);
parse_str($url['query'], $query);
var_dump($query);

【讨论】:

  • @Webbo: parse_url 返回 URL 部分的数组,因此 URL 路径也在其中。您需要进一步区分 URL 的类型。
  • 我宁愿使用正则表达式来完成所有工作
【解决方案3】:

我不得不为我几周前编写的一个 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;
}

【讨论】:

  • 请不要多次发布您的答案。而是将其标记为重复项或添加评论,说明如果另一个问题不是完全重复但仍然相关,则有答案。
  • @awoodland:没有问题,感谢您指出将问题标记为重复问题的可能性。
【解决方案4】:

我从领导者的回答完善了正则表达式。它还从所有各种 URL 中获取 ID,但更正确

if (preg_match('%(?:youtube(?:-nocookie)?\.com/(?:[\w\-?&!#=,;]+/[\w\-?&!#=/,;]+/|(?:v|e(?:mbed)?)/|[\w\-?&!#=,;]*[?&]v=)|youtu\.be/)([\w-]{11})(?:[^\w-]|\Z)%i', $url, $match)) {
    $video_id = $match[1];
}

此外,它还能正确处理超过 11 个字符的错误 ID。

http://www.youtube.com/watch?v=0zM3nApSvMgDw3qlxF

【讨论】:

    【解决方案5】:

    使用

     preg_match("#(?<=v=)[a-zA-Z0-9-]+(?=&)|(?<=[0-9]/)[^&\n]+|(?<=v=)[^&\n]+#", $subject, $matches);
    

    【讨论】:

    【解决方案6】:

    您忘记转义斜线字符。所以这个应该做的工作:

    preg_match("#(?<=v=)[a-zA-Z0-9-]+(?=&)|(?<=[0-9]\/)[^&\n]+|(?<=v=)[^&\n]+#", $subject, $matches);
    

    【讨论】:

    • 如果在正则表达式的开头和结尾使用斜杠以外的字符,则不需要转义斜杠,例如#
    【解决方案7】:

    解析 BBcode 的开始参数 (https://developers.google.com/youtube/player_parameters#start)

    示例:[yt]http://www.youtube.com/watch?v=G059ou-7wmo#t=58[/yt]

    PHP 正则表达式:

    '#\[yt\]https?://(?:[0-9A-Z-]+\.)?(?:youtu\.be/|youtube\.com(?:/embed/|/v/|/watch\?v=|/ytscreeningroom\?v=|/feeds/api/videos/|/user\S*[^\w\-\s]|\S*[^\w\-\s]))([\w\-]{11})[?=#&+%\w-]*(t=(\d+))?\[/yt\]#Uim'
    

    替换:

    '<iframe id="ytplayer" type="text/html" width="639" height="360" src="http://www.youtube.com/embed/$1?rel=0&vq=hd1080&start=$3" frameborder="0" allowfullscreen></iframe>'
    

    【讨论】:

      【解决方案8】:

      我没有看到任何人直接解决PHP错误,所以我会尝试解释。

      “未知修饰符'['”错误的原因是您忘记将正则表达式包含在分隔符中。 PHP 只是将第一个字符作为分隔符,只要它是非字母数字、非空白 ASCII 字符。所以在你的正则表达式中:

      preg_match("(?<=v=)[a-zA-Z0-9-]+(?=&)|(?<=[0-9]/)[^&\n]+|(?<=v=)[^&\n]+", $subject, $matches);
      

      PHP 认为您的意思是 ( 作为开始分隔符。然后它会找到它认为是你的结束分隔符,下一个 ) 并假设后面是模式修饰符。但是它发现您的第一个模式修饰符,即第一个 ) 之后的下一个字符是 [[ 显然不是一个有效的模式修饰符,这就是你得到错误的原因。

      解决方案是简单地将您的正则表达式包含在分隔符中,并确保您想要匹配的正则表达式中的任何分隔符都被转义。我喜欢使用 ~ 作为分隔符,b/c 你很少需要在正则表达式中匹配文字 ~

      【讨论】:

        【解决方案9】:

        使用下面的代码

        $url = "" // here is url of youtube video
        $pattern = getPatternFromUrl($url); //this will retun video id
        
        function getPatternFromUrl($url)
        {
        $url = $url.'&';
        $pattern = '/v=(.+?)&+/';
        preg_match($pattern, $url, $matches);
        //echo $matches[1]; die;
        return ($matches[1]);
        }
        

        【讨论】:

        • 它有效!我试过吗?给我任何不符合此标准的示例?
        • 其他相关帖子http://stackoverflow.com/questions/2164040/grab-the-youtube-video-id-with-jquery-match`
        【解决方案10】:

        这对我有用。

        $yout_url='http://www.youtube.com/watch?v=yxYjeNZvICk&blabla=blabla';
        
        $videoid = preg_replace("#[&\?].+$#", "", preg_replace("#http://(?:www\.)?youtu\.?be(?:\.com)?/(embed/|watch\?v=|\?v=|v/|e/|.+/|watch.*v=|)#i", "", $yout_url));
        

        【讨论】:

          猜你喜欢
          • 2011-12-14
          • 2012-10-11
          • 1970-01-01
          • 2015-09-20
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-08-25
          • 2017-09-20
          相关资源
          最近更新 更多