php – sanitize email address

Question:

Assuming the following email address:

$email = "zuúl@ so.pt";

I tried to sanitize it using:

filter_var($email, FILTER_SANITIZE_EMAIL); // zul@so.pt

I also tried:

preg_replace('/[[:punct:]]/', '', $email); // zuúl sopt

The idea is that because the user types an accent or a blank space by mistake, he is not forced to go "back" to rectify the address, as this type of scenario can be controlled by the application, taking the work out of the user.

Question

How to sanitize the zuúl@ so.pt email address so that it remains zuul@so.pt ?

Answer:

to sanitize email addresses you can use the preg_replace and iconv functions:

$email = preg_replace('/[^a-z0-9+_.@-]/i', '', iconv('UTF-8', 'ASCII//TRANSLIT//IGNORE', $email));

It is important that you ensure that the input characters are in the expected encoding, either at runtime with setlocale or via environment variables (eg Apache ):

Scroll to Top