This article introduces a problem encountered when using regular expressions in PHP to match email addresses (EMail), and its solution. Friends in need can refer to it.
php regular expression matches email, the code is as follows: <?php $a='/([\w\.\_]{2,10})@(\w{1,}).([a-z]{2,4})/'; $b='1412424545645454545454545k@qq.com'; if(preg_match($a,$b)){ echo "电子邮件合法"; }else{ echo "电子邮件不合法啊"; } //by bbs.it-home.org ?> Copy after login Why is the above output legal? {2,10}Can't we only put 2 to 10 digits here, but the email address above exceeds 10 digits. This regular expression can be matched, and it matches this part '545454545k@qq.com' The first part of 1412424545645454 does not match, so it is still legal. Correct matching can be modified as follows: $a='/^([w._]{2,10})@(w{1,}).([a-z]{2,4})$/';Pay attention to the regular rules: /([w._]{2,10})@(w{1,}).([a-z]{2,4})/ It does not have an assertion, which means that it will match as long as there is a matching part in the string. Therefore, {2,10} can only match 2 to 10 digits, but it will not match the entire string as long as a part of it matches. To determine whether an entire string matches, you need to use assertions. Such as ^ $ /^([w._]{2,10})@(w{1,}).([a-z]{2,4})$/ Note that ^$ is added to the head and tailThe perfect code is as follows: <?php $a='/^([\w\.\_]{2,10})@(\w{1,}).([a-z]{2,4})$/'; $b='1412424545645454545454545k@qq.com'; if(preg_match($a,$b)){ echo "电子邮件合法"; }else{ echo "电子邮件非法"; } //by bbs.it-home.org ?> Copy after login |