Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 [email protected]) come through as <mailto:[email protected]|[email protected]> 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 [email protected], however it seems to fail when working with email addresses like [email protected] (which would come through as <mailto:[email protected]|[email protected]>. In these cases, the function is returning [email protected] 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?

like image 490
James Avatar asked Nov 19 '16 11:11

James


People also ask

How do I extract email addresses from a text string?

Here I introduce you a long formula to extract only the email addresses from the text in Excel. Please do as follows: 1. In the adjacent cell B1, enter this formula =TRIM(RIGHT(SUBSTITUTE(LEFT(A1,FIND (" ",A1&" ",FIND("@",A1))-1)," ", REPT(" ",LEN(A1))),LEN(A1))).

How do I find the regex for an email address?

forEach((item) => { let pattern = (/([a-zA-Z0-9. _-]+@[a-zA-Z0-9. _-]+\. [a-zA-Z0-9_-]+)/gi) if (item.

How do I extract email addresses from an email?

Go to the addons menu inside the Google Spreadsheet, choose Email Address Extract and click Start to launch the extractor addon. Specify the search criteria and all emails that match the rule will be parsed by the extractor. You may use any of the Gmail Search operators to filter messages.


1 Answers

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

$testString = '<mailto:[email protected]|[email protected]>';

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

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

echo $addresses[0];
like image 152
bcmcfc Avatar answered Oct 05 '22 22:10

bcmcfc