电话号码匹配正则表达式

时间:2014-11-03 11:48:48

标签: php regex

我使用下面的正则表达式验证电话号码。 但是下面列出的某些格式不应该无效。

+ 5-555-555-5555, +5.555.555.5555, +5 555 555 5555, +5(555)555 5555, 55555555555,

PHP代码:

$phone_numbers = array( 
    '555-555-5555',
    '5555425555',
    '555 555 5555',
    '1(519) 555-4444',
    '1 (519) 555-4422',
    '1-555-555-5555',
    '1-(555)-555-25555',
    '555 555 5555',
    '(555) 555-5555',
    '(555)555-5555',
    '555-555-5555',
    '555.555.5555',
    '5555555555',
    '5-555-555-5555',
    '5.555.555.5555',
    '5 555 555 5555',
    '55555555555',
    '+5-555-555-5555',
    '+5.555.555.5555',
    '+5 555 555 5555',
    '+5 (555) 555 5555',
    '+55555555555'
);
$regex = "/^(\d[\s-]?)?[\(\[\s-]{0,2}?\d{3}[\)\]\s-]{0,2}?\d{3}[\s-]?\d{4}$/i";

foreach( $phone_numbers as $number ) {
    echo $number . ': ' . ( preg_match( $regex, $number ) ? 'valid' : 'invalid' ) . '<br/>';
}

结果:

555-555-5555: valid
5555425555: valid
555 555 5555: valid
1(519) 555-4444: valid
1 (519) 555-4422: valid
1-555-555-5555: valid
1-(555)-555-25555: invalid
555 555 5555: valid
(555) 555-5555: valid
(555)555-5555: valid
555-555-5555: valid
555.555.5555: invalid
5555555555: valid
5-555-555-5555: valid
5.555.555.5555: invalid
5 555 555 5555: valid
55555555555: valid
+5-555-555-5555: invalid-------------- Should be true
+5.555.555.5555: invalid-------------- Should be true
+5 555 555 5555: invalid -------------- Should be true
+5 (555) 555 5555: invalid  -------------- Should be true
+55555555555: invalid -------------- Should be true

1 个答案:

答案 0 :(得分:1)

$regex = "/^\+?(\d[\s-]?)?[\(\[\s-]{0,2}?\d{3}[\)\]\s-]{0,2}?\d{3}[\s-]?\d{4}$/i";