使用正则表达式删除相对路径斜杠

时间:2010-03-31 13:49:30

标签: html ruby-on-rails ruby regex

我正在尝试从包含多个其他元素的HTML块中删除所有相对图像路径斜杠。

例如

<img src="../../../../images/upload/1/test.jpg />

需要成为

<img src="http://s3.amazonaws.com/website/images/upload/1/test.jpg" />

我正在考虑将其写为rails帮助程序,并将整个块传递给方法,并使用Nokogiri或Hpricot来解析HTML,但我真的不知道。

任何帮助都会很棒

干杯 亚当

3 个答案:

答案 0 :(得分:3)

在给定页面的绝对URL和在该页面上找到的相对路径的情况下构建绝对路径的一种方法:

pageurl = 'http://s3.amazonaws.com/website/foo/bar/baz/quux/index.html'
relative = '../../../../images/upload/1/test.jpg'
absolute = pageurl.sub(/\/[^\/]*$/, '')
relative.split('/').each do |d|
  if d == '..'
    absolute.sub!(/\/[^\/]*$/, '')
  else
    absolute << "/#{d}"
  end
end
p absolute

或者,你可以作弊:

'http:/'+File.expand_path(File.dirname(pageurl.sub(/^http:/, ''))+'/'+relative)

答案 1 :(得分:3)

当内置'uri'lib可以为你做这件事时,无需重新发明轮子:

require 'uri'
main_path = "http://s3.amazonaws.com/website/a/b/c"
relative_path = "../../../../images/upload/1/test.jpg"

URI.join(main_path, relative_path).to_s
  # ==> "http://s3.amazonaws.com/images/upload/1/test.jpg"

答案 2 :(得分:1)

这个块可能会有所帮助:

html = '<img src="../../../../images/upload/1/test.jpg />'
absolute_uri = "http://s3.amazonaws.com/website/images"
html.gsub(/(\.\.\/)+images/, absolute_uri)