2014-10-19 92 views
0

即時通訊嘗試在php中驗證電話號碼。要求是(0d)dddddddd或0d dddddddd,其中d是0-9。這是我現在所擁有的特定電話號碼格式的PHP正則表達式

if(!preg_match("/^0[0-9]{9}$/", $phone)) 
{ 
//wrong format 
} 

我試過幾個類似的問題,但仍不能理解正則表達式。 任何人都可以幫我修復正則表達式嗎?

+0

你能否提供一些有效數字的例子 – nu11p01n73R 2014-10-19 07:34:29

+0

當然可以。像(05)12345678或05 12345678 – bisonsausage 2014-10-19 07:41:42

+1

「類似的東西」在討論正則表達式時不夠好。你必須儘可能精確。 – 2014-10-19 07:54:04

回答

1

你可以試試下面的代碼,

if(!preg_match("~^(?:0\d\s|\(0\d\))\d{8}$~", $phone)) 
{ 
//wrong format 
} 

DEMO

說明:

^      the beginning of the string 
(?:      group, but do not capture: 
    0      '0' 
    \d      digits (0-9) 
    \s      whitespace 
|      OR 
    \(      '(' 
    0      '0' 
    \d      digits (0-9) 
    \)      ')' 
)      end of grouping 
\d{8}     digits (0-9) (8 times) 
$      before an optional \n, and the end of the 
         string 
+0

感謝您的解釋,真正幫助那些仍然像我一樣學習的人。欣賞它。 – bisonsausage 2014-10-19 08:04:08

0

試試這個

if(!preg_match("^(?:\(0\d\)|0\d\s)\d{8}$", $phone)) 
{ 
//wrong format 
}