2010-03-12 41 views
2

我想過濾一下我的標題表單上的一些保留字。篩選一些詞

$adtitle = sanitize($_POST['title']); 
$ignore = array('sale','buy','rent'); 
if(in_array($adtitle, $ignore)) { 
$_SESSION['ignore_error'] = '<strong>'.$adtitle.'</strong> cannot be use as your title'; 
header('Location:/submit/'); 
exit; 
  • 如何讓這樣的事情。如果 用戶類型Car for sale銷售 將檢測爲reserved keyword
  • 現在我的當前代碼只能檢測單個關鍵字。

回答

4

你可能尋找一個正則表達式:

foreach($ignore as $keyword) { 
    if(preg_match("/\b$keyword\b/i", $adtitle) { 
    // Uhoh, the user used a bad word!! 
    } 
} 

這也將防止一些誤報,比如「洪流」不來了作爲一個保留字,因爲它包含了「租金」。

+0

謝謝埃裏克;) – wow 2010-03-12 06:40:29

+0

它可能應該是不區分大小寫,也 – 2010-03-12 06:42:52

+0

好一點@Carson – Erik 2010-03-12 07:03:00

1
function isValidTitle($str) { 
    // these may want to be placed in a config file 
    $badWords = array('sale','buy','rent'); 

    foreach($badWords as $word) { 
     if (strstr($str, $word)) return false; // found a word! 
    } 
    // no bad word found 
    return true; 

} 

如果你想匹配的話只有(不是部分匹配以及,如換句話說內),試試這個修改如下

一個
function isValidTitle($str) { 

     $badWords = array('sale','buy','rent'); 

     foreach($badWords as $word) { 
      if (preg_match('/\b' . trim($word) . '\b/i', $str)) return false; 
     } 

     return true; 

    } 
+0

豈不是標誌詞「洪流」,因爲「出租」?這就是爲什麼我以字界限進行正則表達式。 – Erik 2010-03-12 06:34:58

+0

@Erik是的,但他沒有指定是否應該匹配部分單詞。如果他願意,他可以用'preg_match('/ \ b'。$ word。'\ b /')替換。 – alex 2010-03-12 06:37:08

+0

應該可能不區分大小寫 – 2010-03-12 06:43:31

1

$ adtitle =消毒($ _ POST [ '標題']);

$ ignoreArr = array('sale','buy','rent'); (!strpos($忽略,$ adtitle)==假)

的foreach($ ignoreArr爲$忽略){
如果{

$_SESSION['ignore_error'] = '<strong>'.$adtitle.'</strong> cannot 

是用作您的標題';頭像('Location:/ submit /');頭像('位置:/提交/');

exit;

這應該有效。雖然沒有測試過。

0

怎麼這麼簡單的東西:

if (preg_match("/\b" . implode("|", $ignore) . "\b/i", $adtitle)) { 
    // No good 
} 
+0

警告:implode()[function.implode]:會在那裏 – wow 2010-03-12 06:47:33

+0

@bob你在說什麼?沒有錯誤。 – 2010-03-12 20:05:40

4

您也可以嘗試這樣的事:

$ignore = array('sale','rent','buy'); 
$invalid = array_intersect($ignore, preg_split('{\W+}', $adtitle)); 

然後$無效將包含在標題中使用的所有的保留字的列表。如果你想解釋爲什麼標題不能使用,這可能很有用。

編輯

$invalid = array_intersect($ignore, preg_split('{\W+}', strtolower($adtitle)); 
如果你想

區分大小寫的匹配。

+1

+1好的解決方案 – 2010-03-12 20:02:17