Php 搜索“最有效的方法”;“坏名字”;在用户';姓名
我有一个我正在开发的应用程序,用户可以在其中为自己选择一个名字。我需要能够过滤掉“坏”的名字,所以我现在就这样做:Php 搜索“最有效的方法”;“坏名字”;在用户';姓名,php,regex,Php,Regex,我有一个我正在开发的应用程序,用户可以在其中为自己选择一个名字。我需要能够过滤掉“坏”的名字,所以我现在就这样做: $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++;
$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这样的数组中),并搜索用户名以查看该单词是否在其名称中。我对正则表达式不太在行,我能想到的唯一方法就是把它全部放在一个似乎效率很低的循环中。有人有更好的主意吗?我想我需要弄清楚如何用数组搜索字符串
$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
}
这对我来说非常有用我确实试着编辑我的帖子来添加代码行,但你抢先了我一步mellamokb:psome我在那里读到了一篇有用的漫画/文章,内容是关于简单的“坏词”过滤是如何把事情搞得一团糟并捕获无害的词的。当然,我现在找不到了当然。@superaldreams谢谢,我知道里面有“屁股”。干得好,JT。
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;
}