2015-04-23 27 views
0

我想開發一個郵政編碼發現器,郵政編碼由4位數字和兩個字母組成。如果郵政編碼正確,用戶將收到我們在該地區提供的確認信息。如果沒有,我們不會在那裏傳達的信息。基於帶有錯誤的數組的郵政編碼

如果郵政編碼沒有包含正確的標準,那麼輸入正確的郵政編碼爲4位數字和2個字母。

這裏是PHP的一個粗略的樣機:

<?php 
if($_SERVER['REQUEST_METHOD'] == "POST") 
{ 
    $postcode = array(6458,7493,6002,7520); 
    if(in_array($_POST['postcode'],$postcode)) 
    { 
      echo 'We deliver on that district'; 
    } 
    else 
    { 
     echo 'This order can not be delivered in that area'; 
    } 
} 


function IsPostcode($value) { 
return preg_match('/^[1-9][0-9]{3} ?[a-zA-Z]{2}$/', $value); 
} 

if(IsPostcode($_POST['postcode'])) { 
    echo 'Correct Zip code'; 
} 
else { 
    echo 'Incorrect zip code enter 4 letters and 2 numbers'; 
} 

?> 

<form method="post" action="<?php echo $_SERVER['PHP_SELF']?>"> 
<input type="text" name="postcode" /> 
<input type="submit" value="verstuur" /> 
</form> 

在此先感謝

+0

它總是格式爲數字,數字,數字,字母,字母? –

+0

這是什麼問題? – chris85

+0

問題是如何在用戶沒有用數字,數字,數字,數字,字母,字母填寫郵政編碼時顯示錯誤消息? 如果用戶沒有填寫正確的標準(4位數字2個字母)我想顯示一條錯誤消息。 – hzrcan

回答

0

試試這個

<?php 
if($_SERVER['REQUEST_METHOD'] == "POST") { 
    $postcode = array(6458,7493,6002,7520); 
    if(preg_match('/^[1-9][0-9]{3} ?[a-zA-Z]{2}$/', $_POST['postcode'])) { 
     if(in_array($_POST['postcode'],$postcode)) { 
      echo 'We deliver on that district'; 
     } else { 
      echo 'This order can not be delivered in that area'; 
     } 
    } else { 
     echo 'Incorrect zip code enter 4 letters and 2 numbers'; 
    } 
} 
?> 
<form method="post" action="<?php echo $_SERVER['PHP_SELF']?>"> 
    <input type="text" name="postcode" /> 
    <input type="submit" value="verstuur" /> 
</form> 

應該先檢查是否符合您的正則表達式,如果它然後檢查它們是否在允許範圍內。您的正則表達式與當前允許的地址不匹配,因此這些全部將是This order can not be delivered in that areaIncorrect zip code enter 4 letters and 2 numbers

您也不需要只返回本機PHP函數結果的函數。

+0

謝謝!它的工作原理! – hzrcan