2013-12-12 119 views
0

我在Wordpress上嘗試這個,我成功地將youtube的URL轉換爲嵌入,但我想要做的是檢查第一個如果URL是嵌入然後離開它和如果它不是很好,那麼它應該被轉換爲嵌入,轉換部分已經完成了,我的問題是,我不知道如何去比較,我想這:檢查URL是否匹配模式

$video = $user_details->get('embed_code'); 
      $search  = '#(.*?)(?:href="https?://)?(?:www\.)?(?:youtu\.be/|youtube\.com(?:/embed/|/v/|/watch?.*?v=))([\w\-]{10,12}).*#x'; 
      $replace = 'http://www.youtube.com/embed/$2'; 

      if(!preg_match($search,$video)){ 
      $url_video = preg_replace($search,$replace,$video); 
      $url_final = '<iframe width="560" height="315" src="'.$url_video.'" frameborder="0" allowfullscreen></iframe>'; 
} 

<div class="youtube_cls"> 
    <?php echo $url_final; ?> 
    </div> 

所以我試圖用preg_match但我不認爲它的作品,任何想法如果$video格式如$search如果不轉換它,如果是,然後離開它?

+0

給'preg_match'一個鏡頭 - 如果它匹配,它返回true,否則返回false。 – brandonscript

+0

我做了,代碼在上面,但它不工作... – Liza

+0

這就是我沒有注意到的。好的,你能給出一個$視頻網址的樣本嗎? – brandonscript

回答

1

您的代碼實際上效果很好 - 只是如果您的匹配不匹配,$url_final沒有設置。

更換對$video的評論,以便在$url_final下看到兩個回顯正確。

$video = "http://www.youtube.com/watch?v=XUdt_aBmkwo"; 
//$video = '<iframe width="560" height="315" src="//www.youtube.com/embed/XUdt_aBmkwo" frameborder="0" allowfullscreen></iframe>'; 
$search = '#(.*?)(?:href="https?://)?(?:www\.)?(?:youtu\.be/|youtube\.com(?:/embed/|/v/|/watch?.*?v=))([\w\-]{10,12}).*#x'; 
$replace = 'http://www.youtube.com/embed/$2'; 
$url_final = $video; //set $url_final to $video so if !preg_match, it still returns 

if(!preg_match($search,$video)) 
{ 
    $url_video = preg_replace($search,$replace,$video); 
    $url_final = '<iframe width="560" height="315" src="'.$url_video.'" frameborder="0" allowfullscreen></iframe>'; 
} 

echo $url_final; 
+0

知道了:)謝謝! +1 – Liza