Home > Article > Backend Development > PHP regular expression method to verify specific age and gender
When developing web applications, validation of user-entered data is very important. One of them is to verify that the data entered by the user conforms to a specific format. This article will discuss how to validate specific age and gender using PHP regular expressions.
For example, we want to verify that the age entered by the user is between 18 and 60 years old. The following is a PHP regular expression to verify the age entered by the user:
/^(1[8-9]|[2-5][0-9]|60)$/
This regular expression contains some regular expression metacharacters. The following is the explanation of these metacharacters:
In the above regular expression, 1[8-9] represents the age group from 18 to 19, 2-5 represents the age group from 20 to 59, and 60 means 60 years old and above, | means or, so the regular expression is validating whether the entered age is between 18 and 60 years old.
Here is an example of PHP code using the above regular expression:
$age_input = '25'; // 用户输入的年龄 $pattern = '/^(1[8-9]|[2-5][0-9]|60)$/'; if (preg_match($pattern, $age_input)) { echo "输入的年龄符合条件。"; } else { echo "请输入正确的年龄。"; }
Now, we want to validate that the gender entered by the user is Be male or female. The following is a PHP regular expression to verify the gender entered by the user:
/^(男|女)$/
In the above regular expression, | represents or, male and female are two optional options, ^ represents the starting position, and $ represents the ending position. This regular expression will return true if the user enters "male" or "female", otherwise it will return false.
Here is an example of PHP code using the above regular expression:
$gender_input = '男'; // 用户输入的性别 $pattern = '/^(男|女)$/'; if (preg_match($pattern, $gender_input)) { echo "输入的性别符合条件。"; } else { echo "请输入正确的性别。"; }
Summary
In this article, we learned how to validate specific age and gender using PHP regular expressions. Validating the format of user input data is very important, it can help you avoid many problems and improve the security of your web application. Therefore, it is essential to understand how regular expressions work and how to use them in your code.
The above is the detailed content of PHP regular expression method to verify specific age and gender. For more information, please follow other related articles on the PHP Chinese website!