-1

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.

cardi777
  • 563
  • 2
  • 9
  • 22
  • https://www.php.net/manual/en/function.explode – Sammitch Mar 02 '21 at 01:29
  • 2
    If the Client can View Source on your page and it has that HTML, the Client can already get the link information. Maybe you want `href='somefile.php'` instead. Then have the PHP page redirect. – StackSlave Mar 02 '21 at 02:19

1 Answers1

1

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/

Phil
  • 157,677
  • 23
  • 242
  • 245
  • is there a way to make this work in PHP 7.1 ? This only works on some servers – cardi777 Apr 20 '21 at 07:34
  • 1
    @cardi777 this already works fine on 7.1 ~ https://3v4l.org/CsPg3. For earlier versions, use `list(, $local, $host) = $matches;` instead of the array destructuring – Phil Apr 20 '21 at 07:37