用于youtube视频ID的PHP正则表达式

时间:2012-07-11 17:53:34

标签: php regex

  

可能重复:
  php regex - find all youtube video ids in string
  Get YouTube video ID from URL w/ PHP

我发现youtube可能有多种格式用于显示网址。我创建了一些php代码,只有当链接只有这个url格式时才会提取视频ID:http://www.youtube.com/watch?v=videoid

我发现这个REGEX用于提取youtube视频ID,但我不确定如何将其应用到我的代码中。我把它放在我的代码中但没有任何反应。如何将其应用于我的代码或整体上可能采用不同的方法?

HERE是我的网站。

但它无法从此网址格式获取视频ID:

latest short format: http://youtu.be/NLqAF9hrVbY
iframe: http://www.youtube.com/embed/NLqAF9hrVbY
iframe (secure): https://www.youtube.com/embed/NLqAF9hrVbY
object param: http://www.youtube.com/v/NLqAF9hrVbY?fs=1&hl=en_US
object embed: http://www.youtube.com/v/NLqAF9hrVbY?fs=1&hl=en_US
watch: http://www.youtube.com/watch?v=NLqAF9hrVbY
users: http://www.youtube.com/user/Scobleizer#p/u/1/1p3vcRhsYGo
ytscreeningroom: http://www.youtube.com/ytscreeningroom?v=NRHVzbJVx8I
any/thing/goes!: http://www.youtube.com/sandalsResorts#p/c/54B8C800269D7C1B/2/PPS-8DMrAn4
any/subdomain/too: http://gdata.youtube.com/feeds/api/videos/NLqAF9hrVbY
more params: http://www.youtube.com/watch?v=spDj54kf-vY&feature=g-vrec

PHP

    <?php

    $vari ='';

    if($_POST)
    {


        $url     = $_POST['yurl'];
        $parsed_url = parse_url($url);


        parse_str($parsed_url['query'], $parsed_query_string);
        $v = $parsed_query_string['v'];

        $hth        = 300; //$_POST['yheight'];
        $wdth       = 500; //$_POST['ywidth'];
        $is_auto    =   0;

    ?>

<p>Iframe Result:</p>   
<?
//Iframe code with optional autoplay

echo  ('<iframe src="http://www.youtube.com/embed/'.$v.'" frameborder="0" width="'.$wdth.'" height="'.$hth.'"></iframe>');

?>

<p>Old way to embedd result: </p>
<?
//Old way to embed code- optional autoplay
echo  ('<embed width="'.$wdth.'" height="'.$hth.'" type="application/x-shockwave-flash" src="http://www.youtube.com/v/'.$v.'" wmode="transparent" embed="" /></embed>');
}
?>

HTML

<form method="post" action="">
URL:&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
<input type="text" value="<?php $url ?>" name="yurl"> <!--$vari-->
<br>
<input type="submit" value="Generate Embed Code" name="ysubmit">
<br>
</form>

1 个答案:

答案 0 :(得分:1)

尝试上一个问题的答案:

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