Skip to content

Instantly share code, notes, and snippets.

@zealot128
Last active December 22, 2015 15:39
Show Gist options
  • Select an option

  • Save zealot128/6494174 to your computer and use it in GitHub Desktop.

Select an option

Save zealot128/6494174 to your computer and use it in GitHub Desktop.
# normal regex with unnamed groups -> JS/PHP,Pearl
/(\/v\/|\/embed\/|watch?.*v=)([A-Za-z0-9\-_]*)|youtu\.be\/([A-Za-z0-9\-_]*)/
# normal regex with named groups
m = /(\/v\/|\/embed\/|watch?.*v=)(?<id>[A-Za-z0-9\-_]*)|youtu\.be\/(?<id>[A-Za-z0-9\-_]*)/
m.match("http://youtu.be/fat9235")[:id]
# -> fat9235
### Rails example usage
def youtube_link_tag(link, opts={})
options = { width: 280, height: 265 }
regex = /(\/v\/|\/embed\/|watch?.*v=)(?<id>[A-Za-z0-9\-_]*)|youtu\.be\/(?<id>[A-Za-z0-9\-_]*)/
return "" if link.blank?
id = link[regex, :id]
return "" if id.blank?
content_tag :div, class: "video-iframe" do
content_tag :iframe, "", width: options[:width], height: options[:height], src: "//www.youtube.com/embed/#{id}?wmode=opaque", frameborder: 0
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment