这是我的代码:
$valid = true;
$len = strlen($packet->username);
if($len > 16 or $len < 3){
$valid = false;
}
for($i = 0; $i < $len and $valid; ++$i){
$c = ord($packet->username{$i});
if(($c >= ord("a") and $c <= ord("z")) or
($c >= ord("A") and $c <= ord("Z")) or
($c >= ord("0") and $c <= ord("9")) or $c === ord("_") ){
continue;
}
$valid = false;
break;
}
if(!$valid or $this->iusername === "rcon" or $this->iusername === "console"){
$this->close("", "§ePlease make sure your username is longer then §a3§e characters\n§eand only uses numbers and letters§7.");
return;
}
检查用户名以确保其有效。这段代码太慢了,它循环$ len次,导致在我的主线程上无所事事的几秒钟。任何人都知道任何解决方案,以使这更快和更快可能会删除循环?
答案 0 :(得分:1)
使用它:
$username = 'admin';
$valid = preg_match('/^[\w\d]{3,16}$/',$username);
if(!$valid){
echo 'Bad character in your username !';
}
$invalidUsername = array(
'admin',
'root',
'localhost'
);
if(in_array($username, $invalidUsername)) {
echo "Username is not valid !";
}
return true;
答案 1 :(得分:1)
简单的正则表达式:
$valid = (preg_match('/[^A-Z0-9_]/i', $username) === 0);
检查任何非字母/数字/下划线的内容。如果找不到任何内容(0匹配),则用户名有效。否则它无效。