2012-02-26 270 views
1

,如果我的數據庫my_table (id,word)如下代碼比較兩次項

my_table (id,word)

,我已經發布了一些文本稱爲 $name$comment然後我想知道,如果$name和/或$comment有任何喜歡的單詞我已經保存在我的數據庫my_table (id,word)

$name = "Manal Nor"; 
$comment = "Hello lovely world"; 

我現在可以申請它只有一個入口例如$name

$name = "Manal Nor"; // As example no bad words 

$sql = "SELECT * FROM my_table"; 
$result = mysql_query($sql); 

$nameArray = explode(" ", $name); 
$countname = count($nameArray); 
$checkname = 0; 

while ($row = mysql_fetch_assoc($result)) { 

    for ($i=0;$i<$countname;$i++) { 

     if (strcasecmp($nameArray[$i], $row['word']) == 0) { 
      $checkname = 1; 
     } 

    } 

} 

if ($checkname == 1) { 
    echo "banned"; 
    exit; 
} 
else { 
    echo "passed"; 
} 

現在的問題如何應用它的兩個$name和/或$comment,這樣我可以給echo "banned";如果任$name和/或$comment有任何的不好的話在my_table

回答

2

原線訣竅這裏將是對單詞字符兩個變量與preg_split()分裂,並使用所產生的陣列形成IN()子句來查詢。

// Strip non-alpha, space characters 
$name = preg_replace("/[^a-zA-Z ]/", "", $name); 
$comment = preg_replace("/[^a-zA-Z ]/", "", $comment); 

$namewords = explode(" ", $name); 
$commentwords = explode(" ", $comment); 
// Stick them together and escape 
$allwords = array_merge($namewords, $commentwords); 

// Surround each word in quotes 
$allwords = array_unique($allwords); 
$allwords = array_map(function($w) {return "'$w'";}, $allwords); 
$allwords = implode(",", $allwords);  

// Builds a query like 
// SELECT * FROM my_table WHERE word IN ('all', 'words', 'from', 'comment', 'and', 'name'); 
$result = mysql_query("SELECT word FROM my_table WHERE word IN($allwords)"); 

if ($result) { 
    // If any rows were returned, the input contained a bad word. 
    if (mysql_num_rows($result) > 0) { 
     // Contains bad words. Ban user. 
    } 
} 
+0

這是個好主意,非常有幫助,思維敏捷,我用我的真實網站代碼進行了測試,效果非常好。 – 2012-02-26 19:16:43

1

在評論中添加世界。替換

$nameArray = array_merge(explode(" ", $name), explode(" ", $comment)); 
+0

完美的作品太〜非常感謝米庫拉什·迪特 - 這是簡單快速有效。 – 2012-02-26 19:22:03