Home > Software engineering >  Preg_replace plus and dots in gmail
Preg_replace plus and dots in gmail

Time:05-04

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: (?:\.|\ .*)(?=.*?@gmail\.com)

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'] );

CodePudding user response:

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 gmail.com 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" => "sar ah .black . @gmail.com"];
$mail['email'] = preg_replace($pattern, '',  $mail['email'] );

print_r($mail['email']);

Output

[email protected]

CodePudding user response:

And if you want your match to work, you can add to @The fourth bird answer :

preg_replace($pattern, '',  $mail['email'] ,-1,$changes);
if ($changes>0) {
    echo "Mail changed";
}
  • Related