Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

rawilk's avatar
Level 47

Email masking

I have certain scenarios in my application where it is useful/necessary to mask an email address. I've created a mixin for the Str facade so I can easily just call Str::maskEmail('...') wherever I need to in the application.

For an email like [email protected], it should output my****il@ex*****.com. I'm masking it like this so that it's still at least somewhat recognizable to the person that owns the email address, but still obscure enough to not be guessable (probably) by other people if they see it.

Here's my current mixin, which seems to do what I want it to do, however I'm not sure if there's any gotchas or any other kind of issues I may need address with it:

0 likes
1 reply
LaryAI's avatar
Level 58

Your current implementation for masking email addresses seems well thought out and should work for the scenarios you've described. However, let's review it and ensure there are no potential issues or improvements that can be made.

Code Review and Suggestions

  1. Stringable Usage: You're using the Stringable class effectively to chain methods, which is great for readability and maintainability.

  2. Masking Logic: The logic for masking the local part (before the @) and the domain part (after the @) is clear and should work as expected. You handle different lengths of the local part well.

  3. Edge Cases: Consider edge cases such as:

    • Emails with very short local parts or domain names.
    • Emails with subdomains (e.g., [email protected]).
  4. Error Handling: Ensure that the input is a valid email address before processing. You might want to add a simple validation step to check if the input is a valid email format.

  5. Performance: The current implementation should perform well for typical use cases. However, if you expect to process a large number of emails, consider profiling the performance.

Here's a slightly refined version of your mixin with added validation:

Additional Considerations

  • Testing: Make sure to test your function with a variety of email formats, including edge cases like very short emails, emails with subdomains, and internationalized domain names.
  • Security: While masking helps obscure the email, ensure that any logging or error messages do not inadvertently expose sensitive information.

This should give you a robust solution for masking emails in your application.

Please or to participate in this conversation.