James James - 15 days ago 6
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

bob@example.com
) comes through as
<mailto:bob@example.com|bob@example.com>
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
bob@example.com
, however it seems to fail when working with email addresses like
bob.jones@example.com
(which would come through as
<mailto:bob.jones@example.com|bob.jones@example.com>
.
In these cases, the function is returning
jones@example.com
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

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];
Comments