Search code examples
phpemailpreg-replacesecurity-by-obscurity

php obscure email address with modifications


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:firstbit@secondbit.com">[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 firstbit@secondbit.com 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.


Solution

  • 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 firstbit@secondbit.com 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/