我有一個變量$content
包含一段混合文本和HTML img標記和URL。如何使用Perl製作條件正則表達式全局替換?
我想做條件字符串注入做一些替換。
例如,假設$content
包含
ABC <img src="http://url1.com/keep.jpg">
DEF <img src="http://random-url.com/replace.jpg">
GHI <img src="http://url2.com/keep.jpg">
我想編輯$content
並使其
ABC <img src="http://url1.com/keep.jpg">
DEF <img src="http://wrapper-url.com/random-url.com/replace.jpg">
GHI <img src="http://url2.com/keep.jpg">
我對URL的正則表達式條件的列表,以保持:上述白名單匹配。除白名單外的任何圖像URL都將使用封裝網址前綴進行編輯。
我的想法是:
if image tags matched in $content {
if match is in 'whitelist'
do nothing
else
inject prefix replacement
}
我不知道如何使有條件的正則表達式的全局替換,因爲一切都在一個單行字符串變量。
我需要在Perl中實現它。
其他信息:
我的 '白名單' 是目前唯一5行,基本上含有關鍵字和域。
以下是我一直在爲匹配「白名單」所做的工作。
例如。
if ($_ =~ /s3\.static\.cdn\.net/) {
# whitelist to keep, subdomain match
}
elsif ($_ =~ /keyword-to-keep/) {
# whitelist to keep, url keyword match
}
elsif ($_ =~ /cdn\.domain\.com/) {
# whitelist to keep, subdomain match
}
elsif ($_ =~ /whitelist-domain\.net/) {
# whitelist to keep, domain match
}
elsif ($_ =~ /i\.whitelist-domain\.com/) {
# whitelist to keep, subdomain match
}
else {
# matched, do something about it with injection
}
一個不那麼完美的解決方案,我能想到的是在全球範圍內帶有前綴注射代替所有的img網址。
然後做另一個全局替換,通過匹配「白名單」來刪除前綴。
有沒有更有效的解決方案來解決我的問題?
謝謝。
你真的需要爲這個適當的HTML解析器。請顯示您的*正則表達式條件列表* – Borodin
原始問題修改了一些正則表達式條件我一直在使用檢查'白名單'保持。 – KDX