The previous article introduced you to " Let's talk about the regular expression function in PHP? How to use it (with code) 》, this article continues to introduce to you how we can customize the regular expression that matches mobile phone numbers in PHP?
How do we customize the regular expression that matches mobile phone numbers in PHP?
As for mobile phone numbers, we all know that in mainland China, they usually start with 1, and the middle two digits may be 3 4 5 7 8; if the second digit is 3, the third digit It may be 0-9. If the second digit is 4, the third digit may be 7.
If the second digit is 5, the third digit may be 0-8. If the second digit is 7. The third digit is 0-8. If the second digit is 8, the third digit may be 0-9. The next 8 digits can be any combination. When we get the mobile phone number, we need to perform regular matching and enter ( $pattre), for mobile phone numbers, we need exact matching, so we need to add (^$), we start with 1 and end with \d{8}. At this time, we need to add brackets and modify them. If we say The third digit is 3, then our third digit can be 0-9, which is our first case
Next, we enter a field and then match;
Code demonstration:
<?php /* 第一位1 第二位3 4 5 7 8 第三位0-9 7 0-8 01235678 0-9 后八位0-9任意 */ $phone =' 12345678901 ' ; $pattern = '/^1(?:3[0-9])\d{8}$/S'; $result = preg_match($pattern, $phone); echo '匹配结果为:' . $result;
The demonstration results are as follows:
The demonstration results show that our matching result is 0, obviously we did not match successfully;
If I change the input field to 133..., we run it again and find that the matching result is 1;
$phone ='13345678901';
The demonstration results are as follows:
By analogy, as long as we do not exceed the range of 0-9, the matching result can be 1;
If our second number is 4, then our third number can only be 7, so When we need to change the code to 47, the code is as follows:
$pattern = '/^1(?:3[0-9]|47)\d{8}$/S';
When we change 131 to 141, we will find that the matching result is 0 (the code displays the result as follows), because we have declared that if our second number is If 4, then our third number can only be 7. When our output is 147, we will find that the matching result is 1;
##The code is as follows:$phone ='14745678901'; $pattern = '/^1(?:3[0-9]|47)\d{8}$/S';
$phone ='15045678901'; $pattern = '/^1(?:3[0-9]|47|5\d)\d{8}$/S';
$phone ='17045678901'; $pattern = '/^1(?:3[0-9]|47|5\d|7[0-35-8])\d{8}$/S';
$phone ='17045678901'; $pattern = '/^1(?:3[0-9]|47|5\d|7[0-35-8]|8\d)\d{8}$/S';
PHP Video Tutorial"
The above is the detailed content of How do we customize the regular expression for matching mobile phone numbers in PHP? (with code). For more information, please follow other related articles on the PHP Chinese website!