如何在youtube上使用preg_replace显示视频

时间:2014-07-01 15:31:02

标签: php iframe preg-replace preg-match

我想在Youtube上显示一个视频,当我看到Firefox html代码中 Inspect Element 中的代码是正确的时,我使用preg_replace替换任何**link**<iframe src="link"></iframe>没有工作,我也不知道为什么。我的代码如下。感谢您的帮助或建议。

$string = "This is video on youtube **http://www.youtube.com/watch?v=wKTBUmrwYDs**";
$string = preg_replace("/\*\*([\w]+:\/\/[\w-?&;#~=\.\/\@]+[\w\/])\*\*/i",'<iframe width="420" height="315" src="$1" frameborder="0" allowfullscreen></iframe>',$string);
echo $string;

这也不起作用。

$string = preg_replace("/\*\*([\w]+:\/\/[\w-?&;#~=\.\/\@]+[\w\/])\*\*/i","<object width=\"420\" height=\"315\"><param name=\"movie\" value=\"$1?hl=en_US&amp;version=3&amp;rel=0\"></param><param name=\"allowFullScreen\" value=\"true\"></param><param name=\"allowscriptaccess\" value=\"always\"></param><embed src=\"$1?hl=en_US&amp;version=3&amp;rel=0\" type=\"application/x-shockwave-flash\" width=\"420\" height=\"315\" allowscriptaccess=\"always\" allowfullscreen=\"true\"></embed></object>",$string);

1 个答案:

答案 0 :(得分:0)

这应该有效:

<?php
$string = "This is video on youtube **http://www.youtube.com/watch?v=wKTBUmrwYDs**";

preg_match( '#http(s?)://(((www\.)?youtube\.com)|(youtu\.be))/((watch.*(\?|\&)v=([^&]+))|((embed/)?([a-z0-9\-_]+))|)#i' , $string , $matches );

$youtube_id = array_pop( $matches );

$iframe_tag = '<iframe width="420" height="315" src="'.$youtube_id.'" frameborder="0" allowfullscreen></iframe>';