Search code examples
phpregexemail-validation

Regex to match multiple emails separated by space or puncts


I need a regex to match multiple email address separated by space(s) and/or puncts. The email addresses are into a string. I'm trying this, but it doesn't works

^(\s[[:punct:]])*([a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,6}){1}(\s[[:punct:]])*$

Text could be like this:

abcd@abcd.ef, abcd@abcd.ef abcd@abcd.ef

Or even like this

Lorem ipsum dolor sit abcd@abcd.ef amet, consectetur, abcd@abcd.ef, adipiscing elit. Vestibulum consectetur fringilla mi ac dignissim. Nulla at est quam. abcd@abcd.ef Sed enim.


Solution

  • you could replace the ^ and $ anchors with something that doesn't force the email to be both first and last in the line...

    like \b (word boundry)

    \b(\s[[:punct:]])*([a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,6}){1}(\s[[:punct:]])*\b
    

    or nothing at all ?

    (\s[[:punct:]])*([a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,6}){1}(\s[[:punct:]])*
    

    http://rubular.com/r/AMnr2kzp09

    or simply

    (\b[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,6}\b)
    

    since the {1} was restricting the number of emails you could match between ^ and $