Sanitize email address

3

Assuming the following email address:

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

I tried to clean it using:

filter_var($email, FILTER_SANITIZE_EMAIL); // [email protected]

I've also tried:

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

The idea is that because the user type an accent or white space by mistake is not forced back "back" to rectify the address because this type of scenarios can be controlled by the application taking the work to the user. / p>

Question

How to sanitize email address zuúl@ so.pt so that it stays [email protected] ?

    
asked by anonymous 21.10.2014 / 15:03

2 answers

1

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 through environment variables (eg Apache ):

    
21.10.2014 / 15:51
0

Using the iconv (English) function that allows you to convert a string to a specific charset :

iconv('UTF-8', 'ASCII//TRANSLIT', "zuúl@ so.pt"); // zu?l@ so.pt

Now, you have to indicate which locale (English) where the language must be collapsed so that the accented characters do not result in ? :

setlocale(LC_ALL,'pt_PT.utf8');
iconv('UTF-8', 'ASCII//TRANSLIT', "zuúl@ so.pt"); // zuul@ so.pt

Finally, this applies to the first response @Willy Stadnick to also remove spaces:

setlocale(LC_ALL,'pt_PT.utf8');
preg_replace('/\s/', '', iconv('UTF-8', 'ASCII//TRANSLIT', "zuúl@ so.pt"));  // [email protected]

Note: The solution in this answer deals only with spaces and accents. Special characters are not removed.

    
21.10.2014 / 16:50