2012-07-11 65 views
0

可能重复:
php regex - find all youtube video ids in string
Get YouTube video ID from URL w/ PHPPHP正则表达式YouTube视频ID

我已经意识到,YouTube可能有显示的URL几个格式。我创建了一些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> 
+0

你做了什么调试?你可以展示一个[最小测试用例](http://sscce.org),? – 2012-07-11 17:57:17

+0

你需要输出url:''应该是'<?php echo $ url; ?> – 2012-07-11 17:58:14

+0

和http://stackoverflow.com/questions/7221485/get-youtube-video-id-from-url-w-php – mario 2012-07-11 18:01:04

回答

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

是的,我会遵循这个例子。 – techAddict82 2012-07-11 19:13:46

+1

但在嵌入iframe格式的代码时,它不起作用。