Extract email address from string - php

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 [email protected]";

$emails = extract_emails_from($text);

print(implode("\n", $emails));

?>

This will work.

Thanks.


Try this

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

see demo here

Second method

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

See demo here


Parsing e-mail addresses is an insane work and would result in a very complicated regular expression. For example, consider this official regular expression to catch an e-mail address: http://www.ex-parrot.com/pdw/Mail-RFC822-Address.html

Amazing right?

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

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

So,

$to = 'Wez Furlong <[email protected]>, [email protected]';
var_dump(mailparse_rfc822_parse_addresses($to));

would yield:

array(2) {
  [0]=>
  array(3) {
    ["display"]=>
    string(11) "Wez Furlong"
    ["address"]=>
    string(15) "[email protected]"
    ["is_group"]=>
    bool(false)
  }
  [1]=>
  array(3) {
    ["display"]=>
    string(15) "[email protected]"
    ["address"]=>
    string(15) "[email protected]"
    ["is_group"]=>
    bool(false)
  }
}

Tags:

Php