电话号码Regex条件



我需要创建一个正则表达式函数,根据这些条件检查在电话号码字段中输入的电话号码。

•如果数字以6、8或9开头,再加上7位数字•或者如果号码以+656、+658或+659开头,再加上7位

所以基本上它的新加坡电话号码+65是国家代码6、8或9是电话号码的唯一起始数字。

我试过下面的代码,但它不起作用。

add_filter( 'gform_phone_formats', 'sg_phone_format' );
function sg_phone_format( $phone_formats ) {
$phone_formats['sg'] = array(
'label'       => 'Singapore',
'mask'        => false,
'regex'       => '/^[689]d{7}$/D|/^(+656)d{7}$/D|/^(+658)d{7}$/D|/^(+659)d{7}$/D',
);

return $phone_formats;
}

谢谢!

我会对新加坡数字使用以下正则表达式模式:

^(?:+65)?[689][0-9]{7}$

示例脚本:

$number = "+6587654321";
if (preg_match("/^(?:+65)?[689][0-9]{7}$/", $number)) {
echo "MATCH";
}

因此,基本上,regex匹配的集合条件可以通过交替一组与所需字符或数字匹配的集合来找到,如:

<code>
//$regex = '/+65+[?:6?8:?:9]+[0-9]{3}+[0-9]{4}/'; //wrong 
// Edited the following lines
$regex = '/(?:+65[6|8|9]+[d]{7})|(?:+65[689][-|s|/][0-9]{3}+[-|s|/][0-9]{4})/';
$phone = '+6561234567,+6587654321,+659-432-1567,+6594321567,+659 765 4321,+658/765/1234,+659--432--1567,+6555?:?1231234'; //test string
//Match $var against a regular expression
preg_match_all($regex, $phone, $matches, PREG_SET_ORDER, 0);

//var_dump
var_dump($matches) . " n";
//print_r
print_r ($matches) . " n";
//echo single value array();
echo $matches[0][0];
echo "<br />";
echo $matches[1][0];
echo "<br />";
echo $matches[2][0];
echo "<br />";
echo $matches[3][0];
echo "<br />";
echo $matches[4][0];
echo "<br />";
echo $matches[5][0];
echo "<br />";
echo $matches[6][0];
</code>

上述代码的结果如下:

<pre>
//var_dump
array(6) { [0]=> array(1) { [0]=> string(11) "+6561234567" } [1]=> array(1) { [0]=> string(11) "+6587654321" } [2]=> array(1) { [0]=> string(13) "+659-432-1567" } [3]=> array(1) { [0]=> string(11) "+6594321567" } [4]=> array(1) { [0]=> string(13) "+659 765 4321" } [5]=> array(1) { [0]=> string(13) "+658/765/1234" } }
//print_r
Array ( [0] => Array ( [0] => +6561234567 ) [1] => Array ( [0] => +6587654321 ) [2] => Array ( [0] => +659-432-1567 ) [3] => Array ( [0] => +6594321567 ) [4] => Array ( [0] => +659 765 4321 ) [5] => Array ( [0] => +658/765/1234 ) )
//echo single value array();
+6561234567
+6587654321
+659-432-1567
+6594321567
+659 765 4321
+658/765/1234
</pre>

您可以通过设置特定条件来匹配字符串,从而轻松匹配更个性化的正则表达式或任何带有s

<code>
// add more characters to regex to match +659-432-1567
$regex = '/+65[6|8|9]+[-][0-9]{3}+[-][0-9]{4}/';
</code>

修改后的正则表达式的结果将是

<pre>
array(1) { [0]=> array(1) { [0]=> string(13) "+659-432-1567" } }
Array ( [0] => Array ( [0] => +659-432-1567 ) )
+659-432-1567 //echo one match out of six
</pre>

最新更新