问题
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,}))$/"
回答1:
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
回答2:
Don't use a regular exprssion.
Use PHP's filter_var functions:
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo "This ($email) email address is considered valid.\n";
}
Ref: http://php.net/manual/en/filter.examples.validation.php
You may choose to use a type="email" input on the client side. Disabling validation with the novalidate attribute on the form prevents the browser from changing the appearance of inputs based on the validity of their contents, but still allows you to use JavaScript to test.
var statusDiv = document.getElementById("status");
document.getElementById("email").addEventListener("change", function(evt) {
statusDiv.textContent = this.checkValidity() ? "Valid" : "Not valid";
});
<form novalidate>
<label for="email">Email</label>
<input type="email" autocomplete="email" id="email">
</form>
<div id="status"></div>
来源:https://stackoverflow.com/questions/43083055/convert-javascript-regex-to-php-regex