2012-07-11 61 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格式的代碼時,它不起作用。