Sanitize email address

Asked

Viewed 123 times

3

Assuming the following email address:

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

I tried to proceed to sanitize the same by making use of:

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

I tried too:

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

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

Question

How to sanitize your email address zuúl@ so.pt to keep [email protected] ?

2 answers

1


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

$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):

  • 1

    It seems to me that he’s also talking about special characters, not just spaces

  • @Cesarmiguel attention failure my... already corrected the answer :)

  • A doorway of #zuúl@ so.pt results in: [email protected] using setlocale(LC_ALL,'pt_PT.utf8'). Impeccable.

0

Using the function iconv (English) that allows us to make the conversion of a string for a charset specific:

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

Now, it is necessary to indicate which locale (English) where the language must be collected so that 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 @Willy Stadnick’s first reply 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.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.