Extract comma separated emails from string

Extract email addresses from string and make sure to get only email address:

<?php

$email_string = "other@example.com,  another@example.com, non-email, bad@email";

$emails = array_filter(array_map(function($email){
    return filter_var($email, FILTER_SANITIZE_EMAIL);
}, explode(",", $email_string)),function($email){
  return filter_var($email, FILTER_VALIDATE_EMAIL);
});


// Output
// array:2 [
//   0 => "other@example.com"
//   1 => "another@example.com"
// ]

Leave a Comment