I have a variable $content
containing a paragraph of mixed text and HTML img tags and URLs.
I would like to make conditional string injection to do some replacement.
For example, suppose $content
contains
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">
I would like to edit $content
and make it
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">
I have a list of regex conditions for URLs to keep: the said whitelist matches. Any image URL other than the whitelist will be edited with a wrapper-url prefix.
My idea was:
if image tags matched in $content {
if match is in 'whitelist'
do nothing
else
inject prefix replacement
}
I don't know how to make conditional regex global replacement since everything is in a single-line string variable.
I need to implement this in Perl.
Additional information:
My 'whitelist' is only currently 5 lines, basically containing keyword and domains.
Here's what I've been doing for matching the 'whitelist'.
eg.
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
}
A not so elegant solution I can think of is to globally replace all img urls with the prefix injection.
Then do another global replacement to remove the prefix by matching against the 'whitelist'.
Is there a more efficient solution to my problem?
Thanks.