I’d like to allow users to paste in a list of new line separated contacts and have an array of names and emails generated efficiently.
Let’s say the possibilities of the entries are:
John, foo@corp.com
foo@corp.com, John
John foo@corp.com
foo@corp.com John
foo@corp.com // will have the [name] key empty
John // will not be considered if there is no email
Currently my solution is to explode by \n then explode by commas then guess where the email and names are. I admit that this is totally unreliable and that’s why i’d like to see how others can approach this.
The array i’m trying to come up with is like:
array(
[0] => array(
[name] => John,
[email] => foo@corp.com
)
[1] => ...
)
Any ideas?
instead of using explode to split the strings, you may want to look into using a regex split:
http://www.php.net/manual/en/function.preg-split.php
This way you can split the string by space, comma, or both all in one line of code. would probably look something like this:
Then you can check each field with filter_var() to see which is the email address.
http://www.php.net/manual/en/function.filter-var.php