How to replace Youtube urls in text with embeded code (in PHP)?
This is what I've got so far:
<?php
$content = "word1 http://www.youtube.com/watch?v=yqfKe-67foQ&feature=related word2 http://www.youtube.com/watch?v=2vq7gDEn99Y&feature=related word3 http://www.youtube.com/watch?v=nW5HxgMYRto\nhttp://www.youtube.com/watch?v=8Uc2lpH0iZ0&feature=fvhl";
$pattern = '/http:\/\/www\.youtube\.com\/watch\?(.*)v=([a-zA-Z0-9_\-]+)(\S*)/i';
$replace = '<object width="480" height="385"><param name="movie" value="http://www.youtube.com/v/$2&hl=en_US&fs=1"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" v开发者_如何学Calue="always"></param><embed src="http://www.youtube.com/v/$2&hl=en_US&fs=1" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="480" height="385"></embed></object>';
$content = preg_replace($pattern, $replace, $content);
echo $content;
?>
I honestly have no idea why it doesn't work. Some help would be appreciated. Thanks.
You just have to make *
non-greedy:
http:\/\/www\.youtube\.com\/watch\?(.*?)v=([a-zA-Z0-9_\-]+)(\S*)
See "Watch out for greediness".
Try this simple function for URL replacement
function youtube($string)
{
return preg_replace(
'#(http://(www.)?youtube.com)?/(v/|watch\?v\=)([-|~_0-9A-Za-z]+)&?.*?#i',
'<iframe title="YouTube video player" width="480" height="390" src="http://www.youtube.com/embed/$4" frameborder="0" allowfullscreen></iframe>',
$string
);
}
echo youtube('http://www.youtube.com/watch?v=VWsjWCt1PsQ');
echo youtube('http://youtube.com/watch?v=VWsjWCt1PsQ');
echo youtube('http://youtube.com/v/VWsjWCt1PsQ');
echo youtube('http://www.youtube.com/v/VWsjWCt1PsQ');
I would just create a string with a configured embed code. Link attribute could be #LINK#
, width="#WIDTH#"
. Than replace all parameters with your own value. It could be much more comfortable to use. Or you can simply use a youtube embed code generator for that.
精彩评论