PHP solution:
<?php
// example code
$html=<<<EOT
<p>
<a class="cta" href="...">CTA Button</a>
</p>
<p>
<a class="dontreplaceme" href="...">CTA Button</a>
</p>
<p><a class="cta" href="...">
CTA Button</a>
</p><p><a class="cta" href="...">CTA Button</a></p>
<p><a class="cta" href="...">CTA Button</a></p>
EOT;
$delim = 'class="cta"';
// remove white spaces between tags
$html = explode($delim, preg_replace('/\>\s+\</m', '><', $html));
$new = [];
foreach($html as $seg) {
// check end of segment for a match
if(strcmp(substr($seg, -6), '<p><a')>0) {
$seg = substr($seg,0,-6).'<p ' . $delim . '><a';
}
$new[]= $seg;
}
$new = implode("",$new);
print_r($new);
Example: https://www.tehplayground.com/XPVv3i8kRxXI0mJ7
Javascript solution (archived) since you want a PHP one
This will run after the page has rendered and will remove 'cta' from the 'a' tags and place it in the closest 'p' parent
window.addEventListener('load', () => {
document.querySelectorAll('a.cta')
.forEach(e=>{
e.classList.remove('cta');
e.closest('p').classList.add('cta');
});
})
Which compresses down to a tidy one-liner
window.addEventListener('load', () => { document.querySelectorAll('a.cta').forEach(e=>{e.classList.remove('cta');e.closest('p').classList.add('cta');}); })