Home > Article > Backend Development > Practical tips for PHP development: digital validation regularity
Practical tips for PHP development: Numeric verification rules
In the process of PHP development, we often encounter situations where the numbers entered by the user need to be verified. At this time Using regular expressions for number validation is a common and effective way. This article will introduce how to use PHP to write regular expressions for numerical verification and provide specific code examples for reference.
First, we need to clarify the number type that needs to be verified. In actual development, common number verification includes integers, floating point numbers, and numbers in a specific range. The following describes how to write the corresponding regular expressions.
Verify integers:
To verify whether the input is an integer, you can use the following regular expression:
$pattern = '/^d $/'; // Match one or more numbers
In the above regular expression, ^d $
represents a string of numbers from the beginning to the end of the string. Use the preg_match()
function to verify the input:
$input = '123'; if (preg_match($pattern, $input)) { echo 'Input is an integer'; } else { echo 'The input is not an integer'; }
Verify floating point numbers:
If you need to verify whether the input is a floating point number, you can use the following regular expression:
$pattern = '/^d ( .d )?$/'; // Match the integer part and the decimal part
In the above regular expression, ^d (.d )?$
means that the integer part can have one or more digits, and the decimal part can have zero or one decimal point plus one or more digits. Also use the preg_match()
function to verify:
$input = '3.14'; if (preg_match($pattern, $input)) { echo 'Input is floating point number'; } else { echo 'The input is not a floating point number'; }
Verify a specific range of numbers:
If you need to verify whether the input is within a specific range, you can use the following regular expression:
$min = 1 ; $max = 100; $pattern = '/^[1-9]d{0,1}$|^100$/'; // Match numbers between 1-100
In the above regular expression, ^[1-9]d{0,1}$|^100$
means that the number can be one or two digits starting with 1-9, or 100. The verification code is as follows:
$input = '50'; if (preg_match($pattern, $input)) { echo 'Input between 1-100'; } else { echo 'The input is not between 1-100'; }
Through the above example, we can see how to use regular expressions in PHP to validate numbers. In actual development, the matching rules of regular expressions are adjusted according to specific needs to achieve accurate input verification. I hope this article can help readers perform digital verification operations more efficiently in PHP development.
The above is the detailed content of Practical tips for PHP development: digital validation regularity. For more information, please follow other related articles on the PHP Chinese website!