使用preg_match验证电话号码格式


Using preg_match to validate phone number format

我在制作一个函数来验证电话号码是否采用这种确切格式(xxx)xxx-xxxx时遇到了问题。

我的尝试是使用preg_match来确认数字是给定的格式,但是我在模式上有问题。

preg_match("/^([0-9]){3}[0-9]{3}-[0-9]{4}$/", $field)

我想我的问题是我不知道如何处理preg_match中的括号

需要转义括号:'(')

试试这个:

$n = "(123)456-3890";
$p = "/'('d{3}')'d{3}-'d{4}/";
preg_match($p,$n,$m);
var_dump($m);

可以通过下面的代码进行所有的数字验证,

<?php
$array = array(
'0 000 (000) 000-0000',
'000 (000) 000-0000',
'0-000-000-000-0000',
'000 (000) 000-0000',
'000-000-000-0000',
'000-00-0-000-0000',
'0000-00-0-000-0000',
'+000-000-000-0000',
'0 (000) 000-0000',
'+0-000-000-0000',
'0-000-000-0000',
'000-000-0000',
'(000) 000-0000',
'000-0000',
'+9981824139',
9981824139,
919981824139,
'+919981824139',
'qwqwqwqwqwqwqw'
);
foreach($array AS $no){    
            var_dump( ( preg_match( '/'d?('s?|-?|'+?|'.?)(('('d{1,4}'))|('d{1,3})|'s?)('s?|-?|'.?)(('('d{1,3}'))|('d{1,3})|'s?)('s?|-?|'.?)(('('d{1,3}'))|('d{1,3})|'s?)('s?|-?|'.?)'d{3}(-|'.|'s)'d{4}/', $no )
            ||
            preg_match('/([0-9]{8,13})/', str_replace(' ', '', $no))
            ||
            ( preg_match('/^'+?'d+$/', $no) && strlen($no) >= 8 && strlen($no) <= 13 ) )
          );
    }
//var_dump (preg_match('/([0-9]{8,12})/', '99818241') );
//var_dump( strlen(9981) );
//var_dump (preg_match('/^'+?'d+$/', '+12345678') );
//var_dump (preg_match('/^'+?'d+$/', '12345678') );

这将验证您的所有类型的电话号码,输出将是

bool(true)
bool(true)
bool(true)
bool(true)
bool(true)
bool(true)
bool(true)
bool(true)
bool(true)
bool(true)
bool(true)
bool(true)
bool(true)
bool(true)
bool(true)
bool(true)
bool(true)
bool(true)
bool(false)