Table of Contents
PHP 验证实例
您的输入:
Home Backend Development PHP Problem How to verify the email and URL in the form in PHP form learning?

How to verify the email and URL in the form in PHP form learning?

Oct 29, 2021 pm 02:56 PM
php form validation

In the previous article, I brought you "How to verify the required fields in the form when learning PHP forms?" ", which introduces in detail the knowledge about how to verify the required fields in the form in PHP. In this article, we will continue to look at how to verify the email and URL in the form. I hope everyone has to help!

How to verify the email and URL in the form in PHP form learning?

In the previous article we have learned how to verify the required information, that is, the required fields. We need to know that when we fill in the information, although some data are not Required, but this information has format requirements, such as mobile phone number or website address, etc. Such information cannot be filled in casually. How can we complete the verification of this information at this time?

At this time we will use regular expressions to verify the right-click and URL information in the form. If you are not sure about regular expressions, you can click on "Regular Expression Video Tutorial" to learn. Let me briefly introduce to you some knowledge of regular expressions that we will use when validating form data.

Regular expression

Regular expression is a method of describing the rules of a piece of text. It is not an exact match, but through some Fuzzy matching of 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 that needs to be checked.

preg_matchThe syntax format of the function is as follows:

preg_match ( string $正则 , string $字符串 [, array &$结果] )
Copy after login

What we need to note is: According to the $regular variable, match$ String 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. ^ means the beginning; $ means the end.

Next, let’s look at the application of regular expressions through examples:

<?php
 header("Content-type:text/html;charset=utf-8");    //设置编码
 $str = &#39;date20150121&#39;;
 if (preg_match(&#39;/^date/&#39;, $str)) {
     echo &#39;匹配成功&#39;;
 } else {
     echo &#39;匹配失败&#39;;
 }
 ?>
Copy after login

In the above example, we are matching numbers starting with date. Output result:

How to verify the email and URL in the form in PHP form learning?

Next let’s take a look at preg_matchedeThe third parameter is the matching 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.

Let’s take a look at an example. The example is as follows:

<?php
 header("Content-type:text/html;charset=utf-8");    //设置编码
 $str = &#39;date20150121&#39;;
 if (preg_match(&#39;/^date/&#39;, $str,$mat)) {
     print_r($mat);
 } else {
     echo &#39;匹配失败&#39;;
 }
 ?>
Copy after login

Output result:

How to verify the email and URL in the form in PHP form learning?

In the regular expression Use \w for letters and \d for numbers (\D represents non-digits) to represent

represents one Or multiple, * means 0 or more, ? means yes or no, {n} means specific number, {m, n} means greater than m and less than n.

Examples are as follows:

<?php
 header("Content-type:text/html;charset=utf-8");    //设置编码
 $name = "zhang"; // wang zhu hu ma tan
 
 if (preg_match(&#39;/an|hu/&#39;, $name, $arr)) {
     print_r($arr);
 } else {
     echo &#39;匹配失败&#39;;
 }
 ?>
Copy after login

Output results:

How to verify the email and URL in the form in PHP form learning?

Using or conditions can be used to match strings, if only A single letter or character can be represented by a range. Use [] to represent the value range of a character '/[a0\.]/' can match a or 0 or any string of ..

In addition, regular expressions can also use - 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.

Knowing so much about regular expressions, next we have to verify whether the format of the form is correct.

PHP Validation Name, Email and URL

Validation rules for names are required and can only contain letters and spaces. The E-mail validation rule is required, which must be a valid email address (containing '@' and '.'). The URL validation rule is optional, and if present, it must contain a valid URL. Validation rules for notes are optional, multi-line input fields. A gender validation rule is required and one must be selected.

Then we can write the following code through the above policy expression, which 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. , an example is as follows:

$name = test_input($_POST["name"]);
if (!preg_match("/^[a-zA-Z]*$/",$name)) {
    $nameErr = "只允许字母和空格";
}
Copy after login

The above code can prompt the user to fill in the name format, and then we can use the same method to verify the email and URL.

邮箱名可以是字母、数字、下划线和点组成的任意字符;邮箱要包含@符号,后面的文字按域名规则处理,以下代码将通过简单的方式来检测 e-mail 地址是否合法。如果 e-mail 地址不合法,将输出错误信息,示例如下:

$email = test_input($_POST["email"]);
if (!preg_match("/^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/",$email)) {
    $emailErr = "无效的 email 格式!";
}
Copy after login

以下代码将检测URL地址是否合法 (以下正则表达式运行URL中含有破折号:"-"), 如果 URL 地址不合法,将输出错误信息,示例如下:

$website = test_input($_POST["website"]);
if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%
=~_|]/i",$website)) {
    $websiteErr = "无效的 URL";
}
Copy after login

将上述的验证方法添加到整体的格式中,示例如下:

<!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 id="PHP-nbsp-验证实例">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 id="您的输入">您的输入:</h2>";
 echo $name;
 echo "<br>";
 echo $email;
 echo "<br>";
 echo $website;
 echo "<br>";
 echo $comment;
 echo "<br>";
 echo $gender;
 ?>
 
 </body>
 </html>
Copy after login

通过上述代码,当我们没有按照我们设置的规则填写的话,输出结果如下:

How to verify the email and URL in the form in PHP form learning?

当然作为扩展知识,也可以使用弹窗,只需要在上述示例中的代码做些改动,将输出的字符变成弹窗的格式,示例如下:

<!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 = "<script language=\"javascript\">
        {
        alert(\"姓名是必填的\"); //弹出对话框
        }
        </script>";
     } else {
         $name = test_input($_POST["name"]);
         if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
             $nameErr = "<script language=\"javascript\">
            {
            alert(\"姓名只允许字母和空格\"); //弹出对话框
            }
            </script>";
         }
     }
     if (empty($_POST["email"])) {
         $emailErr = "<script language=\"javascript\">
        {
        alert(\"电邮是必填的\"); //弹出对话框
        }
        </script>";
     } else {
         $email = test_input($_POST["email"]);
         // 检查电子邮件地址语法是否有效
         if (!preg_match("/^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/",$email)) {
             $emailErr = "<script language=\"javascript\">
            {
            alert(\"无效email的格式\"); //弹出对话框
            }
            </script>";
         }
     }
     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 = "<script language=\"javascript\">
            {
            alert(\"无效的URL\"); //弹出对话框
            }
            </script>";
         }
     }
     if (empty($_POST["comment"])) {
         $comment = "";
     } else {
         $comment = test_input($_POST["comment"]);
     }
     if (empty($_POST["gender"])) {
         $genderErr = "<script language=\"javascript\">
        {
        alert(\"性别是必选的\"); //弹出对话框
        }
        </script>";
     } else {
         $gender = test_input($_POST["gender"]);
     }
 }
 function test_input($data) {
     $data = trim($data);
     $data = stripslashes($data);
     $data = htmlspecialchars($data);
     return $data;
 }
 ?>
 <h2 id="PHP-nbsp-验证实例">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 id="您的输入">您的输入:</h2>";
 echo $name;
 echo "<br>";
 echo $email;
 echo "<br>";
 echo $website;
 echo "<br>";
 echo $comment;
 echo "<br>";
 echo $gender;
 ?>
 
 </body>
 </html>
Copy after login

当填写内容不按规定规则是,点击提交,输出结果如下:

How to verify the email and URL in the form in PHP form learning?

How to verify the email and URL in the form in PHP form learning?

How to verify the email and URL in the form in PHP form learning?

如此我们便完成了PHP验证名称、邮件和URL。

大家如果感兴趣的话,可以点击《PHP视频教程》进行更多关于PHP知识的学习。

The above is the detailed content of How to verify the email and URL in the form in PHP form learning?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

7 PHP Functions I Regret I Didn't Know Before 7 PHP Functions I Regret I Didn't Know Before Nov 13, 2024 am 09:42 AM

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

See all articles