Extract email address from string - php

I want to extract an email address from a string, for example:

<?php // code $string = 'Ruchika < ruchika@example.com >'; ?> 

From the line above, I want to get the email address ruchika@example.com .

Please advise how to do this.

+6
source share
6 answers

try it

 <?php $string = 'Ruchika < ruchika@example.com >'; $pattern = '/[a-z0-9_\-\+\.] +@ [a-z0-9\-]+\.([az]{2,4})(?:\.[az]{2})?/i'; preg_match_all($pattern, $string, $matches); var_dump($matches[0]); ?> 

see demo here

Second method

 <?php $text = 'Ruchika < ruchika@example.com >'; preg_match_all("/[\._a-zA-Z0-9-] +@ [\._a-zA-Z0-9-]+/i", $text, $matches); print_r($matches[0]); ?> 

Watch the demo here

+9
source

Parsing email addresses is crazy work and will lead to a very complex regex. For example, consider this official regular expression to catch an email address: http://www.ex-parrot.com/pdw/Mail-RFC822-Address.html

Amazing right?

Instead, there is a standard php function for this called mailparse_rfc822_parse_addresses() and documented here .

It takes a string as an argument and returns an array of an associative array with mapping, address, and is_group.

So,

 $to = 'Wez Furlong < wez@example.com >, doe@example.com '; var_dump(mailparse_rfc822_parse_addresses($to)); 

will give:

 array(2) { [0]=> array(3) { ["display"]=> string(11) "Wez Furlong" ["address"]=> string(15) " wez@example.com " ["is_group"]=> bool(false) } [1]=> array(3) { ["display"]=> string(15) " doe@example.com " ["address"]=> string(15) " doe@example.com " ["is_group"]=> bool(false) } } 
+2
source

Check out these two stackoverflow posts:

No. 1 For further reading.

No. 2 For further reading.

+1
source

try this code.

 <?php function extract_emails_from($string){ preg_match_all("/[\._a-zA-Z0-9-] +@ [\._a-zA-Z0-9-]+/i", $string, $matches); return $matches[0]; } $text = "blah blah blah blah blah blah email2@address.com "; $emails = extract_emails_from($text); print(implode("\n", $emails)); ?> 

It will work.

Thanks.

+1
source

This is based on Niranjan's answer, assuming you have an input email address, and> characters). Instead of using regex to capture email addresses, here I get the text part between the <and> characters. Otherwise, I use the string to get all the email. Of course, I did not do any verification on the email address, it will depend on your scenario.

 <?php $string = 'Ruchika < ruchika@example.com >'; $pattern = '/<(.*?)>/i'; preg_match_all($pattern, $string, $matches); var_dump($matches); $email = $matches[1][0] ?? $string; echo $email; ?> 

Here is a forked demonstration .

Of course, if my assumption is wrong, then this approach will fail. But, based on your data, I believe that you would like to receive emails enclosed inside <and> characters.

0
source

you can also try:

 email=re.findall(r'\ S+@ \S+',' ruchika@example.com ') print email 

where \S means any character without spaces

-1
source

All Articles