过滤一些单词

时间:2010-03-12 06:25:20

标签: php arrays

我想在标题表单上过滤一些保留字。

$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
  • 现在我的当前代码仅检测单个关键字。

5 个答案:

答案 0 :(得分:4)

您可能正在寻找正则表达式:

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

这也可以防止一些误报,例如“洪流”不会成为保留字,因为它包含“租金”。

答案 1 :(得分:4)

你也可以尝试这样的事情:

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

然后$ invalid将包含标题中使用的所有保留字的列表。如果您想解释为什么无法使用标题,这可能很有用。

修改

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

如果你想要不区分大小写的匹配。

答案 2 :(得分: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;

    }

答案 3 :(得分:1)

  

$ adtitle = sanitize($ _ POST ['title']);

     

$ ignoreArr =   阵列( '销售', '买', '租赁');

     

foreach($ ignoreArr as $ ignore){
  if(strpos($ ignore,$ adtitle)!== false){

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

用作你的头衔';

 break;
}  
     

}   头( '位置:/提交/');

     

出口;

这应该有效。虽然没经过测试。

答案 4 :(得分:0)

如此简单的事情:

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