2011-05-09 119 views
0

我需要一些幫助來理解一點正則表達式。我見過這樣正則表達式幫助

preg_match("/^ 

      (1[-\s.])? # optional '1-', '1.' or '1' 
      (\()?  # optional opening parenthesis 
      \d{3}  # the area code 
      (?(2) \)) # if there was opening parenthesis, close it 
      [-\s.]?  # followed by '-' or '.' or space 
      \d{3}  # first 3 digits 
      [-\s.]?  # followed by '-' or '.' or space 
      \d{4}  # last 4 digits 

      $/x",$number) 

我都明白,但不明白如何(?(2) \))真正的工作......西隧呢代碼?和(2)代表。

問題更新...

我讀你的答案..當我改變像

preg_match("/^ 

      (1[-\s.])? # optional '1-', '1.' or '1' 
      \d{3}  # the area code 
      (\()?  # optional opening parenthesis 
      (?(3) \)) # if there was opening parenthesis, close it 
      [-\s.]?  # followed by '-' or '.' or space 
      \d{3}  # first 3 digits 
      [-\s.]?  # followed by '-' or '.' or space 
      \d{4}  # last 4 digits 

      $/x",$number) 

我得到錯誤,如

Compilation failed: reference to non-existent subpattern 

代碼是有anythign毛病碼?

回答

2

(2)指條件#2也可以說第二捕獲組,這意味着在第二()。它條件意味着如果有(那麼必定b )

Read here

(?(1)then|else) 

含義如果第一個捕獲組到目前爲止參加了匹配嘗試,那麼「then」部分必須匹配整個正則表達式才能匹配。如果第一個捕獲組沒有參加比賽,那麼「else」部分必須匹配整個正則表達式才能匹配。

eg: (a)?(?(1)b|c) matches ab, the first c and the second c in babxcac 

Also in PHP

+0

看到我的問題更新.. – Hacker 2011-05-09 05:13:59

+0

@pradeep更好地應用'前瞻'和'看後面'**聲明** – diEcho 2011-05-09 05:20:43

+0

@pradeep我更新我的答案與PHP ..的鏈接,這將確保有助於你理解你正在談論的概念 – diEcho 2011-05-09 05:25:14

3

(2)裝置第二匹配的片段,從這裏:(\()?。因此整條線的工作方式如下:如果第二個片段匹配(意味着有左括號),那麼我們需要確保有右括號。

+0

看到我的問題更新 – Hacker 2011-05-09 05:14:23

1

猜猜它說的是什麼,尋找存儲在第二個結果中的區號,如果是,它也應該關閉。這意味着這可能適用於某種'if result-2 is valid => close,else => nothing'。

正則表達式是不是我最好的朋友,所以我希望我是對的。但我也有苦衷解釋/創建它們,因此,也許任何人都可以在這裏教我的事現在;-)

由方式,如果你谷歌的'PHP正則表達式備忘單',有安靜的一些結果,可能是你的興趣,至少他們對我很有趣。

+0

看到我的問題更新 – Hacker 2011-05-09 05:14:15