php obscure email address with modifications

68 Views Asked by At

Sometimes my content has email addresses in it - but I want to obscure them using javascript.

I have made a javascript solution for the frontend which rebuilds them but only from a certain format.

This is the format I need HTML to be in for email addresses:

<a email-a="firstbit" email-b="secondbit.com"></a>

Javascript then runs some code and converts that HTML to this:

<a href="mailto:[email protected]">[click to email]</a>

So that is all fine. My question is how how do I get php to convert all the email addresses from a HTML variable full of random contents from a WYSIWYG to the different format. As in convert this:

bla bla bla [email protected] bla bla bla

to this:

bla bla bla <a email-a="firstbit" email-b="secondbit.com"></a> bla bla bla 

I guess in the end something like this:

function change_emails($html){
// preg replace?
}


// $html is a variable full of HTML contents
$html = change_emails($html);

I already know how to change an email address in a single string - but i don't know how to change all the email addresses which may be peppered inside a big chunk of contents.

1

There are 1 best solutions below

2
On BEST ANSWER

This uses a reasonably simple regex (from this answer) to detect the email addresses and replace them with your HTML-ish template.

$pattern = "/([a-zA-Z0-9+._-]+)@([a-zA-Z0-9._-]+\.[a-zA-Z0-9_-]+)/";
$template = '<a email-a="%s" email-b="%s">[click to email]</a>';

$str = "bla bla bla [email protected] bla bla bla";

return preg_replace_callback($pattern, function($matches) use ($template) {
    [, $local, $host] = $matches;
    return sprintf($template, $local, $host);
}, $str);

Demo ~ https://3v4l.org/CsPg3


Properly detecting email addresses with regular expressions can be quite complex so if you need something more comprehensive, check out this site ~ http://emailregex.com/