Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace username part in email addresses into asterisks

Tags:

regex

php

How can I convert username in email addresses into asterisks. The first and last letter in the username stay as it is and rest replaced with (*).

Example:

[email protected]

into

m****[email protected]
like image 298
Sajid Avatar asked Jul 08 '15 11:07

Sajid


People also ask

Can I use an asterisk for email address?

You can use the asterisk (*) as a wildcard in email addresses when defining routes and in file names. Wildcards can appear in the name or domain sections of an email address. The following are valid examples: *@*: Valid representation of all email addresses.

How do you add an asterisk to an email?

Here's how it works. Suppose somebody sends you an e-mail message that doesn't really require an answer. However, to be polite, you want to say “thank you.” Instead of putting “Thanks” in the body of your reply, type *Thanks in the subject field of your reply.

Can you use a in an email address?

Answer: There is no way to use an email address with an ampersand, e.. g. one&[email protected], for the Sender Email Address in an Email Campaign email message.


1 Answers

You can do it using look arounds.

/(?!^).(?=[^@]+@)/
  • (?!^) Negative look behind. Checks if the character is not preceded by start of string. This ensures that the first character is not selected.

  • . Matches a single character.

  • (?=[^@]+@) Positive look ahead. Ensures that the single character matched is followed by anything other than @ ( ensured by [^@] ) and then a @

Regex Demo

Example

preg_replace("/(?!^).(?=[^@]+@)/", "*", "[email protected]")
=>  m****[email protected]
like image 164
nu11p01n73R Avatar answered Nov 03 '22 23:11

nu11p01n73R