将常规 Youtube“链接"转换为嵌入视频 [英] Converting a regular Youtube 'link' into an embedded video
问题描述
我的目标:我试图允许用户在我的网站中嵌入指向 Youtube 视频的链接,同时让我控制播放器的设置.
My goal: I am trying to allow users to embed a link to a Youtube video in my site, while giving me control over the player's settings.
我只想通过要求用户提供链接(而不是整个嵌入代码)来做到这一点,我可以从那里以某种方式将该链接粘贴到嵌入代码中.
I would like to do this by only asking the user to supply the link (not the entire embed code), from where I can somehow paste that link into the embed code.
我尝试用一些 Youtube 链接 (http://youtu.be/...
) 做一个简单的替换,但它们不起作用,说电影未加载".有没有可靠的方法来做到这一点?
I've tried doing a simple substitution with a few Youtube links (http://youtu.be/...
) but they don't work, saying 'movie not loaded'. Is there a dependable way to do this?
推荐答案
我经常为客户这样做,其要点是您从 URL 中解析出 ID,然后生成 iframe
HTML 使用这个.
I do this quite often for clients, the gist of it is that you parse out the ID from the URL, then generate the iframe
HTML using this.
def youtube_embed(youtube_url)
if youtube_url[/youtu\.be\/([^\?]*)/]
youtube_id = $1
else
# Regex from # http://stackoverflow.com/questions/3452546/javascript-regex-how-to-get-youtube-video-id-from-url/4811367#4811367
youtube_url[/^.*((v\/)|(embed\/)|(watch\?))\??v?=?([^\&\?]*).*/]
youtube_id = $5
end
%Q{<iframe title="YouTube video player" width="640" height="390" src="http://www.youtube.com/embed/#{ youtube_id }" frameborder="0" allowfullscreen></iframe>}
end
youtube_embed('youtu.be/jJrzIdDUfT4')
# => <iframe title="YouTube video player" width="640" height="390" src="http://www.youtube.com/embed/jJrzIdDUfT4" frameborder="0" allowfullscreen></iframe>
我把它放在一个助手里.根据口味更改高度、宽度和选项.
I put this in a helper. Change the height, width and options to taste.
这篇关于将常规 Youtube“链接"转换为嵌入视频的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!