I have a HTML code in a PHP variable, I need to replace every links that are containted within another tag that has a "obfuscate"
class, eg:
<div class="obfuscate foobar">
<strong>
<a href="https://example.com" class="randomclass" target="_BLANK">test</a>
</strong>
</div>
I need the <a>
tag to be replaced with a <span>
that inherits everything from the original tag, with a "akn-obf-link"
class added, and an obfuscated link passed through base64_encode()
under a "data-o"
attribute, and a "data-b"
attribute that has the value "1"
if the link has a target _blank or "0"
otherwise.
In the example above, the <a>
tag should be converted to:
<span class="akn-obf-link randomclass" data-o="aHR0cHM6Ly9leGFtcGxlLmNvbQ==" data-b="1">test</span>
I already have a code that does that when the <a>
tag itself has the "obfuscate"
class if that might help:
$result = preg_replace_callback('#<a[^>]+((?<=\s)href=(\"|\')([^\"\']*)(\'|\")[^>]+(?<=\s)class=(\"|\')[^\'\"]*(?<!\w|-)obfuscate(?!\w|-)[^\'\"]*(\"|\')|(?<=\s)class=(\"|\')[^\'\"]*(?<!\w|-)obfuscate(?!\w|-)[^\'\"]*(\"|\')[^>]+(?<=\s)href=(\"|\')([^\"\']*)(\'|\"))[^>]*>(.*)<\/a>#miUs', function($matches) {
preg_match('#<a[^>]+(?<=\s)class=[\"|\\\']([^\\\'\"]+)[\"|\\\']#imUs',$matches[0],$matches_classes);
$classes = trim(preg_replace('/\s+/',' ',str_replace('obfuscate','',$matches_classes[1])));
return '<span class="akn-obf-link'.($classes?' '.$classes:'').'" data-o="'.base64_encode($matches[3]?:$matches[10]).'" data-b="'.((strpos(strtolower($matches[0]),'_blank')!==false)?'1':'0').'">'.$matches[12].'</span>';
}, $code);
I need the same but whenever the tag is inside another tag that has the "obfuscate"
class.