How to replace Youtube urls in text with embeded code (in PHP)?

萝らか妹 提交于 2020-01-24 21:31:07

问题


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&amp;hl=en_US&amp;fs=1"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube.com/v/$2&amp;hl=en_US&amp;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.


回答1:


You just have to make * non-greedy:

http:\/\/www\.youtube\.com\/watch\?(.*?)v=([a-zA-Z0-9_\-]+)(\S*)

See "Watch out for greediness".




回答2:


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');



回答3:


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.



来源:https://stackoverflow.com/questions/3245037/how-to-replace-youtube-urls-in-text-with-embeded-code-in-php

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!