I want to extract email address from a string, for example:
<?php // code
$string = 'Ruchika <ruchika@example.com>';
?>
From the above string I only want to get email address ruchika@example.com
.
Kindly, recommend how to achieve this.
Try this
<?php
$string = 'Ruchika < ruchika@example.com >';
$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 < ruchika@example.com >';
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 <wez@example.com>, doe@example.com';
var_dump(mailparse_rfc822_parse_addresses($to));
would yield:
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)
}
}
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));
?>
This will work.
Thanks.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With