2013-10-21 35 views
0

我有一個聯繫表單和一個文本字段供人們輸入其公司/組織的名稱。我想阻止提交表單,如果它包含任何以下詞語的任何或變體:uc,uci,irvine,ucirvine。這是我的腳本:PHP聯繫表格檢測文本字段中的單詞

// company group 
    if(trim($_POST['cmpnyGrp']) === '') { 
     $cmpnyGrpError = '<span class="error">Please enter your company or group name.</span>'; 
     $hasError = true; 
    } else if (isset($_POST['cmpnyGrp'])) { 
     $banned = array('uci', 'uc', 'ucirvine', 'uc-', 'uc ', 'irvine'); 
     $cmpnyGrpError = '<span class="error">If you are UCI, select UC under User Type and enter account string.</span>'; 
     $hasError = true; 
    } else { 
     $cmpnyGrp = trim($_POST['cmpnyGrp']); 
    } 

我知道我做錯了什麼,因爲這是行不通的。我不是一個程序員,但我正在盡力理解要做什麼。任何援助將不勝感激。非常感謝你。

+0

你在哪裏使用$禁止陣列? – 2013-10-21 23:06:33

回答

0

現在,您初始化$banned,然後從不使用它。你需要一個if(in_array($_POST['cmpnyGrp'], $banned) {...}。這將檢查cmpnyGrp的值是否在被禁止的單詞數組中。但是,請注意,這樣的黑名單形式永遠無法檢查每個可能的「uc」變體。

+0

,不會工作。 – 2013-10-21 23:09:43

+0

什麼不工作? – TheWolf

+0

in_array,$ _POST ['cmpnyGrp']不包含任何整個匹配字符串 – 2013-10-21 23:14:16

0

您正在聲明一組被禁止的單詞,但無所作爲。你需要使用像如下東西:

foreach ($banned as $b) { 
    if (strpos($_POST['cmpnyGrp'], $b) !== false) { 
     $cmpnyGrpError = '<span class="error">If you are UCI, select UC under User Type and enter account string.</span>'; 
     $hasError = true; 
     break; 
    } 
} 

if (!isset($hasError)) { 
    $cmpnyGrp = trim($_POST['cmpnyGrp']); 
} 
+0

非常感謝你,這工作很好!這是另一個問題。有沒有添加通配符到被禁止的單詞的方法?例如,如果uc是被禁止的詞,則有人可能進入uc-irvine或uc-riverside。我可以在UC後輸入所有單詞嗎?我希望我有道理。謝謝! – user2292856

0

試試這個:

if(trim($_POST['cmpnyGrp']) === '') { 
    $cmpnyGrpError = '<span class="error">Please enter your company or group name.</span>'; 
    $hasError = true; 
} else { 
    $banned = array('uci', 'uc', 'ucirvine', 'uc-', 'uc ', 'irvine'); 
    $found = false; 
    foreach ($banned as $b) { 
     if (stripos($_POST['cmpnyGrp'], $b)) { 
      $found = true; 
      break; // no need to continue looping, we found one match 
     } 
    } 
    if ($found) { 
     $cmpnyGrpError = '<span class="error">If you are UCI, select UC under User Type and enter account string.</span>'; 
     $hasError = true; 
    } else { 
     $cmpnyGrp = trim($_POST['cmpnyGrp']); 
    } 
}