[英]Phone Number Regex Conditions
我需要創建一個正則表達式 function 來根據這些條件檢查在電話號碼字段中輸入的電話號碼。
• 如果號碼以 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";
}
所以基本上可以通過交替匹配所需字符或數字的出現的一組集合來找到正則表達式匹配的設置條件,如下所示:
<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>
您可以通過設置特定條件輕松匹配更多個性化的正則表達式,通過 escaping 附加字符與\
或任何空白字符與\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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.