Reputation: 2289
I have html like this
<iframe width="560" height="315" src="http://www.youtube.com/embed/Wa6CA3YqV2Q" frameborder="0" allowfullscreen></iframe>
How do i get video id Wa6CA3YqV2Q
with regex? And are there any other ways to achieve this?
UPD:
I have used Nokogiri, and i managed to get http://www.youtube.com/embed/Wa6CA3YqV2Q
, so how do i get id, of video having this link?
Upvotes: 2
Views: 2367
Reputation: 65
The code below will take any vimeo or youtube URL and return the video ID and the provider.
In your model
def parse_video_url(url)
@url = url
youtube_formats = [
%r(https?://youtu\.be/(.+)),
%r(https?://www\.youtube\.com/watch\?v=(.*?)(&|#|$)),
%r(https?://www\.youtube\.com/embed/(.*?)(\?|$)),
%r(https?://www\.youtube\.com/v/(.*?)(#|\?|$)),
%r(https?://www\.youtube\.com/user/.*?#\w/\w/\w/\w/(.+)\b)
]
vimeo_formats = [%r(https?://vimeo.com\/(\d+)), %r(https?:\/\/(www\.)?vimeo.com\/(\d+))]
@url.strip!
if @url.include? "youtu"
youtube_formats.find { |format| @url =~ format } and $1
@results = {provider: "youtube", id: $1}
@results
elsif @url.include? "vimeo"
vimeo_formats.find { |format| @url =~ format } and $1
@results = {provider: "vimeo", id: $1}
@results
else
return nil # There should probably be some error message here
end
end
Then in your controller just call:
@results = @course.parse_video_url(@course.video_url)
# Access the hash with @results[:provider] or @results [:id]
And in your view you can write an IF statement to display the relevant embed code for the provider/id combo.
Upvotes: 5
Reputation: 331
Try this:
string = 'http://www.youtube.com/embed/Wa6CA3YqV2Q'
regex = /^(?:https?:\/\/)?(?:www\.)?\w*\.\w*\/(?:watch\?v=)?((?:p\/)?[\w\-]+)/
match = string.match(regex)
if match
return match[1]
end
return ''
I got it from here and changed it a little bit: Parsing youtube url
Upvotes: 0
Reputation: 2289
Ended with following
string = 'http://www.youtube.com/embed/Wa6CA3YqV2Q'
result = string.split('/').last
Upvotes: 1
Reputation: 10285
While you might be able to parse it with a regex, parsing arbitrary html with regexs is bad unless you really know what you're doing. There's a lot of historical controversy around the subject, search about it if you're interested.
The proper way is to parse the document, there's a great parser for rails:
Upvotes: 0
Reputation: 13610
you can use
string.scan(/src="\S+\/(\w+)"/)[0][0]
but if you're doing a lot of html work i would recommend using a full-on HTML parser like Nokogiri or something perhaps more lightweight.
Upvotes: 0