How to verify email address with PHP regular expression
With the advent of the Internet era, email has become an indispensable communication tool in our daily life and work. However, when using email for communication, how to ensure that the entered email address is in the correct format?
As a widely used scripting language, PHP provides a set of regular expression function libraries that can verify and process various texts, including email addresses. In this article, we will introduce how to verify email addresses using PHP regular expressions.
1. Regular expression verification of email addresses
When using PHP to verify email addresses with regular expressions, we need to use a specific regular expression pattern. The following is a basic regular expression pattern:
/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+.[a-zA-Z]{2,}$/
The meaning of this regular expression pattern is:
2. PHP code example
It is not difficult to use PHP to verify email addresses. Here is a sample code:
function is_valid_email_address($email) { $pattern = '/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+.[a-zA-Z]{2,}$/'; return preg_match($pattern, $email); } $email1 = 'example@domain.com'; $email2 = 'example@domain.co.uk'; if (is_valid_email_address($email1)) { echo $email1 . ' is a valid email address.'; } else { echo $email1 . ' is not a valid email address.'; } if (is_valid_email_address($email2)) { echo $email2 . ' is a valid email address.'; } else { echo $email2 . ' is not a valid email address.'; }
The running results are as follows:
example@domain.com is a valid email address. example@domain.co.uk is a valid email address.
3. Conclusion
This article introduces the method of using PHP regular expressions to verify email addresses, and gives a practical PHP code example. As a PHP developer, learning to use regular expressions to validate various text inputs is one of the essential skills. I hope this article can be helpful to everyone.
The above is the detailed content of How to verify email address with PHP regular expression. For more information, please follow other related articles on the PHP Chinese website!