Picking with preg_match e-mail with special PHP characters

Asked

Viewed 572 times

0

With this code below it does not take emails with underline.

It is possible to modify to it catch including underline and other special characters?

In the example below it returns the value "ca@hotmail.com" and the correct one would be "aline_ca@hotmail.com"

preg_match('/([-.a-zA-Z]{1,30})@([-.a-zA-Z]{1,30})([.]{1})([-.a-zA-Z]{1,10})/', 'asdas asdasd asdas aline_ca@hotmail.com asdasd asdas asdas', $msgPreg1);
    echo trim($msgPreg1[0]);
  • 1

    the purpose is to extract emails from a text or validate an entry (sanitize, filter)?

1 answer

2


Just add _ in regex, another detail is that when using hype inside [] do the "escape", also recommend adding [0-9] (or d) because some emails have numbers, would be like this:

If you want to have underline/underscore in the "user/account name":

/([_\-.a-zA-Z\d]{1,30})@([\-.a-zA-Z\d]{1,30})([.]{1})([\-.a-zA-Z]{1,10})/

The code would look like this:

preg_match('/([_\-.a-zA-Z\d]{1,30})@([\-.a-zA-Z\d]{1,30})([.]{1})([\-.a-zA-Z]{1,10})/', 'asdas asdasd asdas aline_ca@hotmail.com asdasd asdas asdas', $msgPreg1);

If you want to have underline/underscore in the "username/account" and domain:

/([_\-.a-zA-Z\d]{1,30})@([_\-.a-zA-Z\d]{1,30})([.]{1})([_\-.a-zA-Z]{1,10})/

The code would look like this:

preg_match('/([_\-.a-zA-Z\d]{1,30})@([_\-.a-zA-Z\d]{1,30})([.]{1})([_\-.a-zA-Z]{1,10})/', 'asdas asdasd asdas aline_ca@hotmail.com asdasd asdas asdas', $msgPreg1);

Note: preg_match will only return you an email (1 match), to catch more than one use preg_match_all, see the difference in ideone:

Browser other questions tagged

You are not signed in. Login or sign up in order to post.