Preg_replace plus and dots in gmail

spammers driving me crazy. Don’t know how Google allows infinite email aliases just by adding a dot or a plus. So I need to kind of sanitize emails like these:


to this:


The regular expression that works is this:

My email function is $mail[’email’], so how do I match dots and plus in this function if found then remove them and clean them up?

What i’ve found by now…
Works but don’t know how to if this then that

preg_match( '/@gmail\.com$/', $mail['email']
preg_replace('^(?:\.|\+.*)(?=.*?@gmail\.com)$',  $mail['email'] );

>Solution :

Your pattern in anchored, so using ^(?:\.|\+.*)(?=.*?@gmail\.com)$ will not find separate matches.

Also the +.* could match more than only the plus sign, removing more than expected.

You could match either dot or a plus sign using a character class [.+] and assert to the right using a positive lookahead, matching only non whitspace chars except an @ until you encounter the first occurrence of @

See the matches on regex101.

For example:

$pattern = "/[.+](?=[^\s@]*@gmail\.com)/";

$mail = ["email" => ""];
$mail['email'] = preg_replace($pattern, '',  $mail['email'] );



Leave a Reply