Regex for extracing multiple email addresses in PHP
-
01-06-2021 - |
Question
I'm receiving content such as:
"Jane Doe" <jane@doe.com>, "John Doe" <john@doe.com>
And I would like to extract the email addresses:
jane@doe.com, john@doe.com
Currently I have a regex like this:
/<(.*)>/
Which gets everything in between brackets, but it also gets things like:
jane@doe.com>, "John Doe" <john@doe.com
When I used an @ sign in the middle, it also didn't work quite right:
/<(.*)@(.*)>/
I could explode()
based on the comma, but I'm thinking there ought to be a way for preg_match()
to give me what I want. What am I missing in my regex?
Solution
Your regexp is too greedy. Use /<(.*?)>/
instead, or better even something like
/<([^<>]+@[^<>]+)>/
OTHER TIPS
I use this for matching emails, I know there are other expressions out there in the wild that may catch more email address but I find this one quick to type and so far suits all my needs, feel free to give it a try:
/\w+[\.\w]+@\w+[\.\w]+/
You may want to use this with preg_match_all to capture all the addresses
for example:
$string = '"Jane Doe" <jane@doe.com>, "John Doe" <john@doe.com>';
preg_match_all('/\w+[\.\w]+@\w+[\.\w]+/', $string, $matches);
print_r($matches);
Easiest way is to match everything except the final delimeter:
/<([^>]*)>/
You are including too much with the dot. Try this:
/<([^>]*)>/