2010-12-13 68 views
1

示例用戶輸入:如何拒絕用戶輸入一些關鍵字應該被拒絕

  • 住宅sale
  • 汽車爲rent
  • WTB iphone價格便宜

我如何讓我的代碼拒絕上述那樣的輸入?

$title = array('rent','buy','sale','sell','wanted','wtb','wts'); 
$user_title = stripslashes($_POST['title']); 
if (in_array($user_title, $title)) { 
    $error = '<p class="error">Do not include ' . $user_title . ' on your title</p>'; 
} 
+0

我希望這只是作爲一個練習,因爲垃圾郵件防範當然比搜索子字符串更復雜。您可能想要使用插件,如Akismet。 – 2010-12-13 18:06:47

回答

4

如果你希望你拒絕的話是完整的單詞,而不是其他的字的一部分,它被認爲是拒絕,你可以使用Word邊界的正則表達式基礎的解決方案:

// array of denied words. 
$deniedWords = array('rent','buy','sale','sell','wanted','wtb','wts'); 

// run preg_quote on each array element..as it may have a regex meta-char in it. 
$deniedWords = array_map('preg_quote',$deniedWords); 

// construct the pattern as /(\bbuy\b|\bsell\b...)/i 
$pat = '/(\b'.implode('\b|\b',$deniedWords).'\b)/i'; 

// use preg-match_all to find all matches 
if(preg_match_all($pat,$user_title,$matches)) { 

    // $matches[1] has all the found word(s), join them with comma and print. 
    $error = 'Do not include ' . implode(',',$matches[1]);  
} 

Ideone Link

+1

+1表示完整的單詞。謝謝:) – Blur 2010-12-13 17:56:35

+1

+1,這是我想要做的解決方案,但沒有時間。非常優雅,規模很好。 – 2010-12-14 19:45:25

1

您可以使用stripos()

$title = array('rent','buy','sale','sell','wanted','wtb','wts'); 
$user_title = stripslashes($_POST['title']); 

foreach($title as $word) 
{ 
    if (stripos($user_title, $word) !== false) 
    { 
     $error = '<p class="error">Do not include ' . $word . ' on your title</p>'; 
     break; 
    } 
} 
+2

儘管更好地使用'stripos()',否則它會錯過'RENT' – 2010-12-13 17:32:08

+0

+1不使用正則表達式,不是它是一件壞事,它只是有點慢:-) – Bojangles 2010-12-13 17:32:48

+0

@Pekka謝謝,糾正。 – 2010-12-13 17:35:25

0

您還可以使用正則表達式:

if (preg_match("/(rent|buy|sale|sell|wanted|wtb|wts)/is", $user_title)) { 
    $error = '<p class="error">Do not include ' . $user_title . ' on your title</p>'; 
} 
0

您可以使用爆炸(),以詞語的$ user_title分離和檢查每個一個確保它不存在於$ title中。

$invalidWords = ''; 

$words = explode(' ', stripslashes($_POST['title'])); 
foreach($words as $word) { 
    if (in_array($word, $title)) { 
     $invalidWords .= ' ' . $word; 
    } 
} 

if (!empty($invalidWords)) { 
    echo '<p class="error">Do not include the following words in your title: ' . $invalidWords . '</p>'; 
} 

正則表達式可能是最好的,但離手,我不能輕易地弄清楚訂單所需的表達你能夠輸出所有的無效字列表中的用戶。