0

I have the following regular expression in Javascript:

function EMailRegularExpression(txtEMail)
{
    var RegExpression = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+[\.]{1}[a-zA-Z]{2,4}$/;

    if(txtEMail.toString().match(RegExpression)) return true;
    else return false;

}

Anyone knows how to convert this to PHP?

D. Rattansingh
  • 1,569
  • 3
  • 19
  • 30
  • take a look at [preg_match](http://php.net/manual/en/function.preg-match.php) – ArtOsi May 18 '17 at 14:06
  • I'm voting to close this question as off-topic because writing regular expression checks in PHP is well documented across this site and the web. Please make an attempt to write the code, and if you have problems getting it working, post a new question. – AndrewR May 18 '17 at 14:08

1 Answers1

2

You can use:

function some_function($email)
{
    if (preg_match('/^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+[\.]{1}[a-zA-Z]{2,4}$/', $email)) {
        return true;
    } else {
        return false;
    }
}

Or simply as pointed by @AndrewR:

function some_function($email)
{
    return preg_match('/^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+[\.]{1}[a-zA-Z]{2,4}$/', $email);
}
Pedro Lobito
  • 94,083
  • 31
  • 258
  • 268
  • This is an anti-pattern. The `if` statement is redundant. [Returning Boolean values from a function](https://github.com/Rafase282/My-FreeCodeCamp-Code/wiki/Lesson-Returning-Boolean-Values-From-Functions) – AndrewR May 18 '17 at 14:19
  • sure, you can simply use `return preg_match('/^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+[\.]{1}[a-zA-Z]{2,4}$/', $email);` but for some users it may be difficult to read. – Pedro Lobito May 18 '17 at 14:20