开发者

regex - trying to auto embed youtube videos [duplicate]

开发者 https://www.devze.com 2023-04-13 06:24 出处:网络
This question already has answers here: Closed 11 years ago. Possible Duplicate: How to embed YouTube videos in PHP?
This question already has answers here: Closed 11 years ago.

Possible Duplicate:

How to embed YouTube videos in PHP?

function youtube($string)
{
preg_match('#(v\/|watch\?v=)([\w\-]+)#', $string, $match);
  return preg_replace(
    '#((http://)?(www.)?youtube\.com/watch\?[=a-z0-9&_]+)#i',
    "<div align=\"center\"><iframe title=\"YouTube video player\" wid开发者_如何学Pythonth=\"480\" height=\"390\" src=\"http://www.youtube.com/embed/$match[2]\" frameborder=\"0\" allowfullscreen></iframe></div>",
    $string);
}

This function almost works, but since the "&" character is turned into "&amp;" it doesn't quite get rid of the whole URL.

http://www.youtube.com/watch?v=oRcUzu_xdJI&feature=feedu

For example returns

embedded video&amp;feature=feedu

How would I need to modify the second regex?

#((http://)?(www.)?youtube\.com/watch\?[=a-z0-9&_]+)#i


If your problem is just the &amp; in the URL string, then extend the character class in your second regex. It only needs to also replace the ; as well:

#((http://)?(www.)?youtube\.com/watch\?[=a-z0-9&_;]+)#i

It might make more sense to match for \S+ however. There might be other unexpected parameters in that string, and thus more leftovers if your character class is too strict.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号