2012-07-11 69 views
2

我目前正試圖通過url檢索YouTube視頻ID。我創建了一個函數getYoutubeVideoID,它剝離了$url並找到了$sVideoID。問題是,當我回顯變量時,我得到一個空值$ sVideoID。如果我將視頻ID分配給$sVideoID,我如何得到沒有價值的結果?PHP顯示來自YouTube的視頻ID

<?php 

if($_POST) 
{ 

$url  = $_POST['yurl']; 

function getYoutubeVideoID($url) { 
    $sVideoID = preg_replace('~https?://(?:[0-9A-Z-]+\.)?(?:youtu\.be/| youtube\.com\S*[^\w\-\s])([\w\-]{11})  
     (?=[^\w\-]|$)(?![?=&+%\w]*(?:[\'"][^<>]*>| </a>))[?=&+%\w-]*~ix','<a href="http://www.youtube.com/watch?v=$1">YouTube link: $1</a>',$url); 
    return $sVideoID; 
} 

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


?> 

<? 
//Iframe code 

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

?> 

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

你可能在URL其他參數和順序不確定性。例如:http://www.youtube.com/watch?feature=g-all-esi&v=6mgFdn4lfrE – alfasin 2012-07-11 21:20:44

+0

你在哪裏設置'$ sVideoID'? – 2012-07-11 21:31:36

+0

可能重複的[PHP的正則表達式的YouTube視頻ID](http://stackoverflow.com/questions/11438544/php-regex-for-youtube-video-id) – mario 2012-07-11 22:45:17

回答

2

也許我錯了,也許你沒有包含所有的相關數據,但我沒有看到你的代碼w中的任何地方在這裏你執行你創建的功能。

而不是目前你在做什麼,試試這個:

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

你不能簡單地定義一個函數,它會執行並分配變量..你有什麼所具有的功能,在執行時,在它的位置返回一個變量。舉個例子,你可以分配$ VAR的功能return value

$var = getYoutubeVideoID($url); 

,而不是很以上,你甚至可以嘗試這個辦法:

$sVideoID = getYoutubeVideoID($url); 

最後,而不是使用正則表達式像其他人那樣注意,你可以結合使用parse_url()parse_str()從您的網址,以獲取數據:

$arr = parse_url($url); 
parse_str($arr['query'], $output); 
echo $output['v']; 
+1

謝謝!我是php的新學習者。但我使用正則表達式的原因是YT URL有很多格式。我嘗試過'parse_str',但它不夠用。 – CodingWonders90 2012-07-11 21:42:36

+0

@ user1519101我明白了;好吧,我很高興能夠幫到你。 – Daedalus 2012-07-11 21:44:16

2

爲什麼我收到沒有價值的結果爲$ sVideoID

你永遠不分配它(至少在你提供的代碼)。 $sVideoID的代碼位於用戶定義的函數中 - getYoutubeVideoID()。你從來沒有打過電話。 Daedalus在他的答案中提供了一個樣本分辨率。

另一方面...不要使用正則表達式解析URL。還有其他的,更簡單的方法

例如:

+0

作爲提到達達盧斯我使用正則表達式的原因是YT網址有很多格式。我嘗試過parse_str,但它不夠用。 – CodingWonders90 2012-07-11 21:44:37

+0

格式改變的事實是正則表達式是一個糟糕的解決方案的主要原因。使用這些功能將URL分開很容易,並且使用代碼邏輯來提取視頻ID。 – 2012-07-12 03:18:11