正则表达式检测邮箱地址是否正确
题目如题了…… 这个正则完全抄书……所以不多解释。
使用的函数是preg_match
,在PHP 实现中文字符串截取无乱码提及了就不怎么解释了。
电子邮件的正则表达式是:/^\w+@\w+(\.\w+){0,3}$/
源码:
1<!DOCTYPE html>
2<html>
3<head>
4 <meta charset="utf-8">
5 <title>Check Email</title>
6</head>
7<body>
8 <form action="check_email.php" method="post">
9 <input type="text" name="email" placeholder="输入email">
10 <input type="submit" value="提交">
11 </form>
12 <?php
13 if ($_SERVER['REQUEST_METHOD'] === 'POST') {
14 $problem = FALSE;
15 $email = $_POST['email'];
16
17 if (empty($email)) {
18 $problem = TRUE;
19 echo '请输入邮箱';
20 }
21
22 if (!$problem) {
23 checkEmail($email);
24 }
25 }
26
27 function checkEmail($email) {
28 $pattern = '/^\w+@\w+(\.\w+){0,3}$/';
29 if (preg_match($pattern, $email, $matches)) {
30 echo 'All right';
31 } else {
32 echo 'Sorry,Wrong address';
33 }
34 }
35 ?>
36</body>
37</html>
38
评论 (1)
我偏爱 `filter_var()` 函数