Extract email address from string - php

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

<?php // code
$string = 'Ruchika <[email protected]>';
?>

From the above string I only want to get email address [email protected].

Kindly, recommend how to achieve this.


Solution 1:

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

Solution 2:

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)
  }
}

Solution 3:

This is based on Niranjan's response, assuming you have the input email enclosed within < and > characters). Instead of using a regular expression to grab the email address, here I get the text part between the < and > characters. Otherwise, I use the string to get the entire email. Of course, I didn't make any validation on the email address, this will depend on your scenario.

<?php 
    $string = 'Ruchika <[email protected]>';
    $pattern = '/<(.*?)>/i';

    preg_match_all($pattern, $string, $matches);
    var_dump($matches);
    $email = $matches[1][0] ?? $string;
    echo $email;
?>

Here is a forked demo.

Of course, if my assumption isn't correct, then this approach will fail. But based on your input, I believe you wanted to extract emails enclosed within < and > chars.