php使用正则表达式编写程序验证手机号码是否符合要求?要求:请使用自定义函数编写并验证2个手机号码是否符合要求。
时间: 2023-12-06 17:40:46 浏览: 34
可以使用以下自定义函数来验证手机号码是否符合要求:
```php
function validatePhoneNumber($phone) {
if(preg_match('/^1[3456789]\d{9}$/', $phone)) {
return true;
} else {
return false;
}
}
```
上面的函数使用正则表达式来验证手机号码,正则表达式`/^1[3456789]\d{9}$/`表示以1开头,第二个数字为3、4、5、6、7、8、9中的一个,后面跟着9个数字,共11位数字。如果传入的手机号码符合要求,该函数将返回true,否则返回false。
以下是使用该函数验证两个手机号码是否符合要求的示例代码:
```php
$phone1 = '13888888888';
$phone2 = '19999999999';
if(validatePhoneNumber($phone1) && validatePhoneNumber($phone2)) {
echo '两个手机号码均符合要求';
} else {
echo '至少有一个手机号码不符合要求';
}
```
相关问题
使用正则表达式编写程序验证手机号码是否符合要求?要求:请使用自定义函数编写并验证2个手机号码是否符合要求。
可以使用以下正则表达式来验证手机号码是否符合要求:
```python
import re
def check_phone_number(phone_number):
pattern = r'^1[3456789]\d{9}$'
return bool(re.match(pattern, phone_number))
# 测试
print(check_phone_number('13912345678')) # True
print(check_phone_number('19912345678')) # True
print(check_phone_number('12345678901')) # False
```
在这个正则表达式中,`^1[3456789]\d{9}$` 表示:
- `^` 表示匹配字符串的开头;
- `1` 表示匹配数字 1;
- `[3456789]` 表示匹配数字 3、4、5、6、7、8 或 9 中的任意一个;
- `\d{9}` 表示匹配 9 个数字;
- `$` 表示匹配字符串的结尾。
因此,这个正则表达式可以匹配以数字 1 开头,第二个数字为 3、4、5、6、7、8 或 9,后面跟着 9 个数字的手机号码。如果想匹配更多的手机号码格式,可以根据实际情况进行调整。
php使用正则表达式编写程序验证URL地址是否符合要求?要求:请使用自定义函数编写并验证2个URL地址是否符合要求。
Sure, I can help you with that. Here's a sample code for validating URLs using regular expressions in PHP:
```
<?php
function isValidUrl($url) {
$pattern = '/^(https?|ftp):\/\/[^\s\/$.?#].[^\s]*$/i';
return preg_match($pattern, $url) === 1;
}
// Sample usage
$url1 = 'https://www.example.com/index.html';
$url2 = 'ftp://ftp.example.com/test/file.txt';
if (isValidUrl($url1)) {
echo $url1 . ' is a valid URL';
} else {
echo $url1 . ' is not a valid URL';
}
if (isValidUrl($url2)) {
echo $url2 . ' is a valid URL';
} else {
echo $url2 . ' is not a valid URL';
}
?>
```
This code defines a custom function `isValidUrl()` that takes a URL string as input and uses a regular expression pattern to check whether it's a valid URL or not. It returns `true` if the URL is valid and `false` otherwise. You can use this function to validate any number of URLs by passing them as arguments. Note that the regular expression pattern used here is a simplified version and may not catch all edge cases.