<?php
function validate($string){
$s = strtolower($string);
if(!preg_match("/^(?i)[a-z0-9_]*$/", $string)){
#checks if the username contains any strange characters
return "dirty can only have letters a-z, numbers 0-9 and underscores _";
}elseif(!preg_match("/^(?![0-9_]).*$/", $string)){
#checks if the username entered begins with a number or underscore
return "dirty can't begin with a number or underscore";
}elseif(preg_match("/__/", $string)){
#checks if the username has more than 1 consecutive underscores
return "dirty can't have consecutive underscores";
}elseif(substr($string,(strlen($string) - 1), strlen($string)) == "_"){
#checks if the username ends with an underscore
return "dirty can't end with an underscore";
}elseif(strlen($string) < 3){
#checks if the username is less than 3 characters in length
return "dirty must be at least 3 characters long";
}elseif(strlen($string) > 20){
#checks if the username is more than 20 characters in length
return "dirty must be less than 20 characters long";
}else{
#if everything seems to be fine return "clean"
return "clean";
}
}
?>
<?php
$str = "Chris"; #test username
#if the validate function returns the word dirty then you know its found a fault in the username
if(ereg("dirty",validate($str))){
#replace the word 'dirty' with 'username' then print out the error
$error = str_replace("dirty","Username",validate($str));
echo $error;
}else{
#username has no problems
echo "Username is fine.";
}
>