Mithc Mithc - 1 month ago 5
PHP Question

How to separate (and sanitize) emails by commas?

The plot



I'm trying to create a function to get emails from user input. This emails should be separated by commas, but as we all know, we should never trust the user input, so they maybe will put an space between the email addresses and commas or a comma at the end with no email after that comma.

The goal




  1. Get emails from the user input.

  2. Get this list of emails, sanitize them, and save them in an array.

  3. User-input proof (they can even put 20 commas at any position with no email between them, but this won't create an array position).



My rookie attempt



So what I have is this:

<?php
$user_input = 'so@godsnetwork.com, you@are.com,great@people.com, thank@you.io,,email.com,';
$email_array = explode( ',', $user_input );

$sanitized_email_string = '';
$last = end( $email_array );

foreach ($email_array as $i => $email) {
$email = sanitize_email( $email ); // Returns an empty string if is not a valid email

if ( $email )
$sanitized_email_string .= $email . ( ( $last === $i ) ? '' : ',' );
}

$sanitized_array = explode( ',', $sanitized_email_string );


But my problem is that, as I mentioned above, if the user puts commas with no email between them, the real end of the array is not the last valid email. So this creates an extra empty array position.

How can I make this function work?

Answer

Ignore the email business. You take a string. You explode() the string into an array. You then build a NEW string... which you then explode() AGAIN. Why such a pointless waste of resources? Just build an array in the first place:

$valid_emails = array();
foreach ($email_array as $i => $email) {
    $email = sanitize_email( $email );
    if ($email) {
        $valid_emails[] = $email;
    }
}

If the email's not valid, it doesn't get pushed into the array.