2011-06-24 418 views
1

我希望有人能幫助!!!從PHP!ereg和!eregi切換到preg_match

在編碼形式驗證,我得到了錯誤信息"Deprecated: Function ereg() is deprecated in E:\Zacel_Development\sa_model_watch.co.za\insert_newProf.php on line 184"

我做了一些研究,發現我需要改變!eregi和!EREG到的preg_match ...

我也試試這個,但無濟於事......任何人都可以檢查我的代碼,並建議我被困住了!

我的代碼段:

/* Check is numeric*/ 
$regex = "[0-9]{10}"; 
    if(!ereg($regex,$field)){ 
    $form->setError($fieldValue, "* Contact number invalid"); 
    } 

顯然應該爲:

/* Check is numeric*/ 
$regex = "[0-9]{10}"; 
if(!preg_match($regex,$field)){ 
$form->setError($fieldValue, "* Contact number invalid"); 
} 

AND:

/* Check if valid email address */ 
$regex = "^[_+a-z0-9-]+(\.[_+a-z0-9-]+)*" 
    ."@[a-z0-9-]+(\.[a-z0-9-]{1,})*" 
    ."\.([a-z]{2,}){1}$"; 
    if(!eregi($regex,$field)){ 
     $form->setError($fieldValue, "* Email invalid"); 
     } 

顯然應該爲:

/* Check if valid email address */ 
$regex = "^[_+a-z0-9-]+(\.[_+a-z0-9-]+)*" 
    ."@[a-z0-9-]+(\.[a-z0-9-]{1,})*" 
    ."\.([a-z]{2,}){1}$"; 
    if(!preg_match($regex,$field)){ 
     $form->setError($fieldValue, "* Email invalid"); 
     } 

這仍然行不通...我做錯了什麼?

回答

2

你必須打開,並用分隔符閉上你的正則表達式:

這樣:

$regex = "[0-9]{10}"; 

成爲

$regex = "/[0-9]{10}/"; 

如果你想在模式不區分大小寫使用i flag

$regex = "/somepattern/i"; 
+0

Tnx @PeeHaa,這工作奇蹟!你搖滾人! – Celeste

+0

@PeeHaa,這可能聽起來很愚蠢,但是,我已經查看了整個網站,無法找到如何將問題標記爲回答...大聲笑..我只是點擊「回答你的問題」? – Celeste

+0

@Celeste:您可以通過勾選選票下方的複選標記來接受答案。 – PeeHaa

0

這裏你是一些例子:

從ereg,preg_match可以相當嚇倒。在這裏開始是一個遷移提示。

<?php 
if(ereg('[^0-9A-Za-z]',$test_string)) // will be true if characters arnt 0-9, A-Z or a-z. 

if(preg_match('/[^0-9A-Za-z]/',$test_string)) // this is the preg_match version. the /'s are now required. 
?> 
+1

只是爲了避免在閱讀其他代碼時出現混淆:'/'不是明確需要的。你可以選擇你喜歡的每個分隔符。模式的第一個字符總是被視爲分隔符,所以如果你開始使用模式,例如用'〜'這個使用了'''',而不是'/'作爲結尾符號。 – KingCrunch