James James - 10 months ago 46
PHP Question

Retrieve full email address from string

I'm currently building a Slack bot using Laravel, and one of the features is that it can receive an email address and send a message to it.

The issue is that email addresses (e.g

) comes through as
from Slack.

I currently have a function that retrieves the email from this:

public function getEmail($string)
$pattern = '/[a-z0-9_\-\+]+@[a-z0-9\-]+\.([a-z]{2,3})(?:\.[a-z]{2})?/i';
preg_match_all($pattern, $string, $matches);
$matches = array_filter($matches);
return $matches[0][0];

This seemed to be working fine with email addresses like
, however it seems to fail when working with email addresses like
(which would come through as
In these cases, the function is returning
as the email address.

I'm not great with regex, but is there something else I could use/change in my pattern, or a better way to fetch the email address from the string provided by Slack?

Answer Source

Could always take regex out of the equation if you know that's always the format it'll be in:

$testString = '<mailto:bob@example.com|bob@example.com>';

$testString = str_replace(['<mailto:', '>'], '', $testString);

$addresses = explode('|', $testString);

echo $addresses[0];