Search code examples
javascriptphpregexpreg-match

Convert Javascript regex to PHP regex?


I'm using the following regex from emailregex.com to validate emails on my site. It's working like a charm in JS but I'm unable to get it working within PHP.

/^(([^<>()[]\.,;:\s@"]+(.[^<>()[]\.,;:\s@"]+)*)|(".+"))@(([[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}])|(([a-zA-Z-0-9]+.)+[a-zA-Z]{2,}))$/

The issue from what I'm seeing is the backslashes, when adding it in quotes it keeps trying to escape it. Regex101 shows that it is working, it's just a matter of how to get it into PHP.

Any help would be great, thanks!

PHP Code:

$emailRegex = "/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/"

Solution

  • Use single quotes ' around regex text instead of double quotes "

      $emailRegex = '/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/';
    

    Because you have used " in your regex,

    Otherwise you need to escape " also by \"

    Live demo : https://eval.in/763141