Home >Backend Development >PHP Tutorial >Problem analysis of PHP regular expression matching email address

Problem analysis of PHP regular expression matching email address

WBOY
WBOYOriginal
2016-07-25 08:57:551281browse
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
?>

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 tail

The 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
?>


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn