PHP Form - Verification Email and URL
When it comes to verification, we need to know the regular expression:
Regular expression
Regular expression is a method of describing a text rule. It is not an exact match, but a fuzzy match through some specific symbols
In PHP, we use the preg_match function to Perform regular expression matching. One parameter is our regular expression rule, and the second parameter is the text to be checked
preg_match (string $regular, string $character String[, array &$result] )
Function: Match $string variable based on $regular variable. If it exists, return the number of matches and put the matched results into the $result variable. If no result is found, 0 is returned.
^ indicates the beginning; $ indicates the end
Let’s take a look at the code:
<?php header("Content-type:text/html;charset=utf-8"); //设置编码 $str = 'date20150121'; if (preg_match('/^date/', $str)) { echo '匹配成功'; } else { echo '匹配失败'; } ?>
The above code matches numbers starting with date. The matching results are as follows:
Matching successful
preg_matchedeThe third parameter is matched Content, usually we will pass an empty array in, because it is a call by address. After the matching is completed, the specific matching content will be obtained in the array
Example
<?php header("Content-type:text/html;charset=utf-8"); //设置编码 $str = 'date20150121'; if (preg_match('/^date/', $str,$mat)) { print_r($mat); } else { echo '匹配失败'; } ?>
Program running result:
Array ( [0] => date )
In regular expressions, letters are represented by \w and numbers are represented by \d (\D represents non-digits)
• + means one or more
• * means 0 or more
• ? means there or not
• {n} represents the specific number
• {m, n} represents more than m and less than n
Just like the following :
<?php header("Content-type:text/html;charset=utf-8"); //设置编码 $name = "zhang"; // wang zhu hu ma tan if (preg_match('/an|hu/', $name, $arr)) { print_r($arr); } else { echo '匹配失败'; } ?>
Program running result:
Array ( [0] => an )
Using or conditions can be used to match strings. If it is just a single letter or character, you can use a range representation
Use [] Indicates the value range of a character
'/[a0\.]/' can match any string containing a or 0 or .
In addition, regular expressions can also be used - To represent a set of ranges
• [a-z] represents any one of the 26 lowercase letters
• [A-Z] represents an uppercase letter
• [0-9 ] represents a decimal number
Now that we know so much, let’s look at using regular expressions to match the content of the form.
PHP - Validation Name
The following code will detect whether the name field contains letters and spaces in a simple way. If the name field value is illegal, an error message will be output:
$name = test_input($_POST["name"]);
if (!preg_match("/^[a-zA-Z]*$/",$name)) {
$nameErr = "Only letters and spaces allowed";
}
##PHP - Verification Email
Rules: The email name can be any character consisting of letters, numbers, underscores and dots; the email must contain the @ symbol, and the following text is processed according to domain name rules
The following code will check whether the e-mail address is legal in a simple way. If the e-mail address is illegal, an error message will be output:
$email = test_input($_POST["email"]);if (!preg_match("/^ [a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/",$email)) {
$emailErr = "Invalid email format!";
}
PHP - Verification URL
$website = test_input($_POST["website"]);if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0- 9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%
=~_|]/i",$website)) {
$websiteErr = "Invalid URL";
}
We will now combine the knowledge we learned above to verify the data in our form.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>PHP中文网</title> </head> <style> .error {color: #FF0000;} </style> <body> <?php // 定义变量并设置为空值 $nameErr = $emailErr = $genderErr = $websiteErr = ""; $name = $email = $gender = $comment = $website = ""; if ($_SERVER["REQUEST_METHOD"] == "POST") { if (empty($_POST["name"])) { $nameErr = "姓名是必填的"; } else { $name = test_input($_POST["name"]); // 检查姓名是否包含字母和空白字符 if (!preg_match("/^[a-zA-Z ]*$/",$name)) { $nameErr = "只允许字母和空格"; } } if (empty($_POST["email"])) { $emailErr = "电邮是必填的"; } else { $email = test_input($_POST["email"]); // 检查电子邮件地址语法是否有效 if (!preg_match("/^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/",$email)) { $emailErr = "无效的 email 格式"; } } if (empty($_POST["website"])) { $website = ""; } else { $website = test_input($_POST["website"]); // 检查 URL 地址语法是否有效(正则表达式也允许 URL 中的斜杠) if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i",$website)) { $websiteErr = "无效的 URL"; } } if (empty($_POST["comment"])) { $comment = ""; } else { $comment = test_input($_POST["comment"]); } if (empty($_POST["gender"])) { $genderErr = "性别是必选的"; } else { $gender = test_input($_POST["gender"]); } } function test_input($data) { $data = trim($data); $data = stripslashes($data); $data = htmlspecialchars($data); return $data; } ?> <h2>PHP 验证实例</h2> <p><span class="error">* 必需的字段</span></p> <form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>"> 姓名:<input type="text" name="name"> <span class="error">* <?php echo $nameErr;?></span> <br><br> 邮箱:<input type="text" name="email"> <span class="error">* <?php echo $emailErr;?></span> <br><br> 网址:<input type="text" name="website"> <span class="error"><?php echo $websiteErr;?></span> <br><br> 评论:<textarea name="comment" rows="5" cols="40"></textarea> <br><br> 性别: <input type="radio" name="gender" value="female">女性 <input type="radio" name="gender" value="male">男性 <span class="error">* <?php echo $genderErr;?></span> <br><br> <input type="submit" name="submit" value="提交"> </form> <?php echo "<h2>您的输入:</h2>"; echo $name; echo "<br>"; echo $email; echo "<br>"; echo $website; echo "<br>"; echo $comment; echo "<br>"; echo $gender; ?> </body> </html>
If we don’t fill in the rules according to the rules we wrote above, the following prompt will appear: If the information you enter is correct, it will be verified.You can also use regular expressions to match mobile phone numbers. Think about the rules of mobile phone numbers.