2009-12-26 46 views
0

這是我笨功能:preg_replace不工作!

function edit_phone($phone) 
{ 
      if (preg_match('/^\(?[0-9]{3}\)?[-. ]?[0-9]{3}[-. ]?[0-9]{4}$/', $phone)) 
      { 
       return preg_replace("/([0-9]{3})([0-9]{3})([0-9]{4})/", "$1-$2-$3", $phone); 
      } 
      else 
      { 
       $this->CI->validation->set_message('phone', "This must be a 10-digit USA phone number."); 
        return FALSE;  
      } 
} 

這證實/好嗎檢查輸入,但在db不重新格式化。

驗證非常好!但爲什麼這不會返回一個標準的電話號碼?!

+0

也許你不保存edit_phone的返回值? – 2009-12-26 22:57:08

+0

啊,你可能是對的!你能舉個例子嗎?我是新來的...... – 2009-12-26 23:04:29

回答

3

我認爲問題是,它只能與格式1234567890許多工作,但基於的preg_match()調用的正則表達式,凱文還希望以適應像數字:

  • (123)4567890
  • (123)456 7890
  • 123-456-7890

如果是這樣,在preg_replace函數正則表達式()需要像...

preg_replace('/^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/', "$1-$2-$3", $phone)

2

您能否給我們提供您試圖填寫的示例數據?

我用下面的代碼:

$phone = "1234567890"; 
echo preg_replace("/([0-9]{3})([0-9]{3})([0-9]{4})/", "$1-$2-$3", $phone); 

,並得到:

123-456-7890 

這是絕對正確的,據我可以告訴。

+0

我相信邁克爾是正確的。你能告訴我如何獲得回報嗎? – 2009-12-26 23:10:16

+2

'$ phone_number = edit_phone(「1234567890」);'返回值現在在'$ phone_number'中 – 2009-12-26 23:29:42