我正在尝试解析包含 iframe 的字符串,将其 src
属性转换为特殊格式的 Ruby 变量,然后将字符串中的 iframe 替换为以特定方式格式化的 Ruby 变量。到目前为止,我已经写了这个:
def video_parse(string)
if string.include?('youtube.com/?v=')
url = 'youtube.com/?v='
string.gsub!('<iframe>.*</iframe>', video_service('YOUTUBE', vid(string, url)))
end
if string.include?('player.vimeo.com/video/')
url = 'player.vimeo.com/video/'
string.gsub!('<iframe>.*</iframe>', video_service('VIMEO', vid(string, url)))
end
string
end
def vid(string, url)
string.split(url).last.split(/['"]/).first
end
def video_service(service, vid)
"*|#{service}:[$vid=#{vid}]|*"
end
但它并不能取代任何东西。我怀疑我的通配符 iframe 标签选择是错误的,而且我的vid
方法有点笨拙。如何使gsub
中的通配符正常工作?对于奖励积分,我可以更有效地编写它,这样我就不会解析string
以重新格式化 iframe 中的src
吗?
更新
字符串看起来像这样:
string = 'resources rather than creating our luck through innovation.n<br>n<br> n<iframe allowfullscreen="" frameborder="0" height="311" mozallowfullscreen="" name="vimeo" src="http://player.vimeo.com/video/222234444" webkitallowfullscreen="" width="550"></iframe>n<br>n<br>nThat hasn’t stoppe'
第二次尝试看起来像这样,仍然没有替换任何东西:
def mailchimp_video_parse(string)
if string.include?('youtube.com/?v=')
string.gsub!(iframe) { video_service('YOUTUBE', vid(Regexp.last_match[1])) }
end
if string.include?('player.vimeo.com/video/')
string.gsub!(iframe) { video_service('VIMEO', vid(Regexp.last_match[1])) }
end
string
end
def vid(iframe)
iframe.split!('src').last.split!(/"/).first
end
def iframe
'<iframe.*</iframe>'
end
def video_service(service, vid)
"*|#{service}:[$vid=#{vid}]|*"
end
还是没有。
Nokogiri 更安全一点:
d = Nokogiri::HTML(string)
d.css('iframe').each do |i|
if i['src'] =~ %r{(youtube|vimeo).*?([^/]+)$}i
i.replace(video_service($1.upcase, $2)
end
end
puts d.to_html
(但请注意,它的效率低于纯正则表达式解决方案,因为 Nokogiri 将解析整个 HTML。
-
应
/<iframe.*</iframe>/
iframe
方法,以便将其正确识别为正则表达式 -
Regexp.last_match[1]
应在mailchimp_video_parse
方法中Regexp.last_match[0]
-
split!
只需要在vid
方法中split
(Ruby 中没有split!
方法(
编辑方法:
def mailchimp_video_parse(string)
if string.include?('youtube.com/?v=')
string.gsub!(iframe) { video_service('YOUTUBE', vid(Regexp.last_match[0])) }
end
if string.include?('player.vimeo.com/video/')
string.gsub!(iframe) { video_service('VIMEO', vid(Regexp.last_match[0])) }
end
string
end
def vid(iframe)
iframe.split('src').last.split(/"/).first
end
def iframe
/<iframe.*</iframe>/
end