2016-01-13 80 views
0

如何從字符串中將所有https替換爲http紅寶石替換img src https到http

<img src="https 
<img src='https 
<img title="title" src="https 

因爲這種類型的組合

"text <img src='https://image.com/img.jpg' /> text".gsub('<img src="https', '<img src="http') 

會讓HTTPS未置換的。

gsub('https', 'http') 

不好,因爲我不想替換鏈接。

+0

的理想解決方案將是Web服務器重新定向到'https' URL –

+0

如果你只需要正則表達式的GSUB: '.gsub(/

回答

2

使用,而不是一個字符串正則表達式:

mystring = "text <img src='https://image.com/img.jpg' /> text" 

mystring.gsub(/\<img src=("|')https.+("|')/){|match| match.gsub('https','http')} 
=> "text <img src='http://image.com/img.jpg' /> text" 
+0

它的效果很好。謝謝。你能推薦我哪裏可以學習正則表達式嗎? –

+0

@IonVasile:http://stackoverflow.com/tags/regex/info – Jan

1

如果圖像標籤只包含<img src="">(無屬性),你可以Ø以下:

<img.*?src=('|")((?!https)[^"']+)\1 
# look for an image tag literally 
# look for src=" or src=' 
# assure that it is no https (negative lookahead) 
# capture everything up to the previously captured delimiter (quote/double quote) 

這些字符串需要更換。

https://regex101.com/r/nA4yX4/1