AssamGuy
AssamGuy

Reputation: 1593

Extract a string between two characters

I have an output string in this format Fname Lname<[email protected]>. I want to extract the email from here. How can I do that?

Upvotes: 4

Views: 16076

Answers (4)

jensgram
jensgram

Reputation: 31508

Don't reinvent the wheel. Instead, use a parser. mailparse_rfc822_parse_addresses() is made for this specific task by professionals with an in-depth knowledge of the subject (and the possible quirks that you may run into).

Example #1 from the docs:

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

Gives (gentle formatting applied):

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

See also: imap_rfc822_parse_adrlist() and Full name with valid email.

Upvotes: 3

Tatu Ulmanen
Tatu Ulmanen

Reputation: 124868

If you can be sure that the string format is consistent, a simple regular expression will do the trick:

$input = 'Fname Lname<[email protected]>';
preg_match('~<(.*?)>~', $input, $output);
$email = $output[1];

Upvotes: 13

Johannes
Johannes

Reputation: 514

This should print the e-mail address:

if (preg_match("/<\S*>/", $subject, $matches)) {
  echo "E-Mail address: ".$matches[0];
}

Upvotes: -1

George
George

Reputation: 2110

Use functions like substring and explode(easier method than regular expressions and will do the trick):

<?php
$text = 'Fname Lname<[email protected]>';
$pieces = explode('<',$text);
$mail=substr($pieces[1],0,-1);
echo $mail;
?>

Upvotes: 1

Related Questions