簡體   English   中英

使用正則表達式刪除相對路徑斜杠

[英]Using regular expressions to remove relative path slashes

我正在嘗試從包含其他幾個元素的HTML塊中刪除所有相對圖像路徑斜杠。

例如

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

將需要成為

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

我當時想將其編寫為Rails的幫助程序,只是將整個代碼塊傳遞給方法,然后使用Nokogiri或Hpricot來解析HTML,但是我並不知道。

任何幫助都會很棒

干杯亞當

給定頁面的絕對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)

當內置的“ uri”庫可以為您做到這一點時,無需重新發明輪子:

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"

此塊可能會幫助:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM