How to Divide a String in Mail Address Format into Names and Mail Addresses in PHP

Asked 1 years ago, Updated 1 years ago, 72 views

Thank you for your help.
Suppose you have a string in the following email address format:

I would like to get this string in PHP divided into the name part (for example, the "test" part) and the email address part (for example, the "[email protected]" part). Is there any good way?
After all, I guess I have to take it out with a regular expression.
I would appreciate it if you could give me some advice if there is any good way.
Thank you for your cooperation.

php mail

2022-09-30 21:47

3 Answers

I ended up using the library because the regular expressions I answered before were not enough and it was difficult to use regular expressions.
After installing an extension called mailparse, it was easy to obtain by doing the following:

var_dump(mailparse_rfc822_parse_addresses('Test' <[email protected]>'));


2022-09-30 21:47

Hello
without using regular expressions for reasons such as speed. If you want to take something out of the string and you can predict the input value,
I often use explode.

$a="Test <[email protected]>";
$b =explode("<",$a);
echo$b[0].PHP_EOL;
echo str_replace(">", "", $b[1]).PHP_EOL;

I think regular expressions have better visibility in this case.


2022-09-30 21:47

First of all, I wrote it in a regular expression.
However, there may be insufficient points.
If you notice anything, please let me know.

<?php
var_dump(separate_mail_address("\"Test\"<[email protected]>"));

// a function that divides names and e-mail addresses and returns them in an array
function separate_mail_address($address){
// see if a regular expression matches
if(preg_match("/^(.*?)<(.*?)>$/",$address,$matches)===1){
// extract the name of
$name = $matches[1];
// What to do when the name part is not empty?
if($name!==""){
// Remove trailing blanks because up to < is taken out as a single pattern
$name = rtrim($name, "");
// Double quotation is not available for the name part, so delete it.
$name = str_replace('", "", $name);
}
// extract the e-mail address portion of one's e-mail address
$address = $matches[2];
// set names and addresses in an array
$ret = array($name,$address);
// What to do when a regular expression does not match?
} else {
// array and set the addresses passed to
$ret = array($address);
}
// return the result
return$ret;
}
?>


2022-09-30 21:47

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.