Skip to content
Advertisement

Create an array include email

I am trying to create a function to extract email to send but I do not find the solution

Thank you

email type : contact<contact@contact.com>, contact1<contact1@contact.com>

the function

 public static function extractEmail(string $email)
    {
      $pattern = '/(?<=<)(.*?)+(?=>)/';
      $result = preg_match_all($pattern , $email , $matches);


      $result = explode(',', $result);

      if (is_array($result)) {
       foreach ($result as $token) {
        $email = filter_var(filter_var($token, FILTER_SANITIZE_EMAIL), FILTER_VALIDATE_EMAIL);

          if ($email !== false) {
            $emails[] = $email;
          }
        }

        return $emails[0];
      } else {
        return false;
      }
    }

and after I make a loop via foreach.

Advertisement

Answer

You could make use of array_map and array_filter to sanitize email addresses and remove invalid ones:

/**
 * @return string[]
 */
function extractEmails(string $contactString): array
{
    if (!preg_match_all('/<(?<emails>[^>]+)>/', $contactString, $matches)) {
        return [];
    }

    return array_filter(array_map(static function (string $email): ?string {
        $sanitizedEmail = filter_var($email, FILTER_SANITIZE_EMAIL);
        
        return filter_var($sanitizedEmail, FILTER_VALIDATE_EMAIL) ? $sanitizedEmail : null;
    }, $matches['emails']));
}

Usage:

print_r(extractEmails('contact<contact@contact.com>, contact1<contact1@contact.com>'));
// ['contact@contact.com', 'contact1@contact.com']

Basically:

  • preg_match_all gathers all (supposed) email addresses within $matches['email']
  • array_map sanitizes and validates said email addresses (null is returned if one is invalid)
  • array_filter finally removes all null values.

Demo

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement