2012-04-18 47 views
2

我有一个应用程序,正在开发中,用户可以为其自己选择一个名称。我需要能够过滤出“坏”的名字,所以我做这个现在:用户名中搜索“坏名字”的最有效方法

$error_count=0; 

$bad_names="badname1badname2"; 

preg_match_all("/\b".$user_name."\b/i",$global['bad_names'], 
    $matches,PREG_OFFSET_CAPTURE); 

if(count($matches[0])>0) 
{ 
    $error_count++; 
} 

这将告诉我,如果用户的名字是坏的名称列表中,但是,它并没有告诉我如果错误名称本身在用户名中。他们可能会把一个坏词与其他东西结合起来,而我不会察觉它。

什么样的正则表达式(如果我甚至使用正则表达式)我会用这个?我需要能够接受任何错误的名称(最好是像$ bad_names这样的数组),然后搜索用户的名称以查看该单词是否在其名称中。我对正则表达式并不是很满意,我能想到的唯一方法就是把它全部通过一个看起来非常低效的循环。任何人有更好的主意?我想我需要弄清楚如何通过一个数组搜索字符串。

+0

我曾尝试编辑自己的帖子把代码行,但你打我给它mellamokb:P – Phillip 2012-04-18 02:02:02

+0

带我看了一个有用的漫画/条关于如何简单的“坏词”过滤可以搞砸和捕捉无害的单词。当然,我当然无法找到它。 – 2012-04-18 02:17:28

+1

@SurrealDreams [Clbuttic Mistake](http://www.telegraph.co.uk/news/newstopics/howaboutthat/2667634/The-Clbuttic-Mistake-When-obscenity-filters-go-wrong.html) – 2012-04-18 02:32:44

回答

1
$badnames = array('name1', 'name2'); 

// you need to quote the names so they can be inserted into the 
// regular expression safely 
$badnames_quoted = array(); 
foreach ($badnames as $name) { 
    $badnames_quoted[] = preg_quote($name, '/'); 
} 

// now construct a RE that will match any bad name 
$badnames_re = '/\b('.implode('|', $badnames_quoted).')\b/Siu'; 

// no need to gather all matches, or even to see what matched 
$hasbadname = preg_match($badnames_re, $thestring); 
if ($hasbadname) { 
    // bad name found 
} 
+0

恩nvm,我得到它的工作。需要删除/ b。 – Phillip 2012-04-18 03:07:34

0
private static $bad_name = array("word1", "word2", "word3"); 
private static $forbidden_name = array (array of unwanted character strings) 

private static function userNameValid($name_in) { 
    $badFound = preg_match("/\b(" . implode(self::$bad_name,"|") . ")\b/i", $name_in); // checks array for exact match 
    $forbiddenFound = preg_match("/(" . implode(self::$forbidden_name,"|") . ")/i", $name_in); // checks array for any character match with a given name (i.e. "ass" would be found in assassin) 

    if ($badFound) { 
    return FALSE; 
    } elseif ($forbiddenFound) { 
    return FALSE; 
    } else { 
    return TRUE; 
    } 

这对我的伟大工程

相关问题