In PHP, you may be familiar with how to use regular expressions to verify IP addresses. it is composed of numbers ranging from 0 to 25 and separated. The definition is very simple, and the regular expression is also very simple. Next, let's take A look at how the regular expression represents: A ([0-9]? [0-9]) | (1 [0-9] {2}) | (2 [0-4] [0-9]) | (25 [0-5]).) {3} ([0-9]? How to use regular expressions to verify IP addresses in PHP?
IP addresses may all be familiar. they are composed of numbers ranging from 0 to 25 and separated. The definition is very simple, and the regular expression is also very simple.
Next, let's see how the regular expression is represented:
/\ A ([0-9]? [0-9]) | (1 [0-9] {2}) | (2 [0-4] [0-9]) | (25 [0-5]) \.) {3} ([0-9]? [0-9]) | (1 [0-9] {2}) | (2 [0-4] [0-9]) | (25 [0-5]) \ Z/
This is the regular expression that represents the IP address. don't scare away. Next we will explain in detail how it is represented. First, I want to explain that the "/" at the beginning and end is the delimiters, which do not represent anything. \ A and \ Z represent the start and end, respectively. Next, we split the middle part into two segments ([0-9]? [0-9]) | (1 [0-9] {2}) | (2 [0-4] [0-9]) | (25 [0-5]) \.) {3}, this is the first section. we marked the corresponding positions of parentheses in different colors. The last {3} indicates that the content in the RedSquare brackets appears three times. In blue brackets, each digit is represented. \. Indicates the. number itself, that is, the first three digits have a vertex number. Now let's analyze the most important part, how to represent the numbers 0. That is, the content in the blue brackets.
These numbers may be one, two, or three digits. We use the symbol (|). when one or two digits exist, please refer to the first digit ([0-9]? [0-9]). The question mark indicates 0 or 1 occurrence, which indicates a number between 0 and 99. When the number is a three-digit number, we have three more cases: 1-199: we represent (1 [0-9] {2}), 200-249: we represent (2 [0-4] [0-9]), 250-255: we represent (25 [0-5]). These four types can match any one of them in the range of 0 to. the entire front part means that the three numbers 0 to plus the decimal point. The last part is the copy of the preceding number. Only one number. Now we organize it into a function. For reference:
Function checkipaddres ($ ipaddres ){
$ Preg = "/\ A ([0-9]? [0-9]) | (1 [0-9] {2}) | (2 [0-4] [0-9]) | (25 [0-5]) \.) {3} ([0-9]? [0-9]) | (1 [0-9] {2}) | (2 [0-4] [0-9]) | (25 [0-5]) \ Z /";
If (preg_match ($ preg, $ ipaddres) return true;
Return false;
}