Web Development

I had a need to parse bunches of text with requirements to extract usernames from emails, extract emails from texts and extracting text that aren’t emails.

Extracting Usernames from Emails

The string we will have as an example would be me@gistpages.com. We would like to extract me from me@gistpages.com.

    public function extractUsername($email) {
        $string = explode("@", $email);
        array_pop($string);
        return implode("@", $string);
    }

Extracting a Name from a String with Emails

The string we will have as an example would be Thorpe Obazee me@gistpages.com. We would like to extract Thorpe Obazee from Thorpe Obazee me@gistpages.com.

   public function extractName($string) {
        return preg_replace("/[^@\s]*@[^@\s]*\.[^@\s]*/", '', $string);
    }

Extracting Emails from a String

The string we will have as an example would be Thorpe Obazee me@gistpages.com. We would like to extract me@gistpages.com from Thorpe Obazee me@gistpages.com.

   public function extractEmails($string) {
        foreach(preg_split('/\s/', $string) as $token) {
            if (filter_var(filter_var($token, FILTER_SANITIZE_EMAIL), FILTER_VALIDATE_EMAIL) !== false) {
                $emails[] = $email;
            }
        }
        return $emails;
    }