[RandomThings2] [[RandomThings" /> [RandomThings2] [[RandomThings" /> [RandomThings2] [[RandomThings"/>

Regex - Duplicate HTML links and put something after it

128 Views Asked by At

I have a lot of such texts:

<a href="https://mega.co.nz/#![RandomThings1]" target="_blank">[RandomThings2] [<span style="color:#008000;">[RandomThings3]</span>]</a>

I want to transform those into this:

<a href="https://mega.co.nz/#![RandomThings1]" target="_blank">[RandomThings2] [<span style="color:#008000;">[RandomThings3]</span>]</a> <a href="http://no.refer.co/?link=https://mega.co.nz/%23![RandomThings1]" target="_blank">NoRefer</a>

How can I do this?

1

There are 1 best solutions below

3
Wiktor Stribiżew On BEST ANSWER

Since the regex flavor in Search Regex WordPress plug-in is PHP, you can try the following regular expression that assumes you really have some arbitrary text inside square brackets ([RandomThings1]):

(<a\s+[^>]*?href="[^"]*#!(\[.*?\])"[^>]*?>[^<>]*?<span[^>]*?>[^<>]*?<\/span>[^<>]*?<\/a>)

Replace with $1 <a href="http://no.refer.co/?link=https://mega.co.nz/%23!$2" target="_blank">NoRefer</a>.

Here is a demo.

PHP code:

$re = "/(<a\\s+[^>]*?href=\"[^\"]*#!(\\[.*?\\])\"[^>]*?>[^<>]*?<span[^>]*?>[^<>]*?<\\/span>[^<>]*?<\\/a>)/"; 
$subst = "$1 <a href=\"http://no.refer.co/?link=https://mega.co.nz/%23!$2\" target=\"_blank\">NoRefer</a>"; 
$result = preg_replace($re, $subst, $str);