So, im coding something and for the username, and i want to verify if there isnt any other characters then ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890._ // a space too but, there is too much characters to add in a preg_match, and i would like just to verify if there is any other characters then the list i put, but how..?
I tried preg_match, but got tired after i saw all characters when doing Windos . ...there is too much characters...and i just want to simplify my code..so how?
CodePudding user response:
RegEx will do the trick.
Edit: I see now that you'd like to allow only specified characters, iterating the string will be sufficient for this.
<?php
function validateUsername($username, $minLength = 3, $maxLength = 20) {
$allowed_chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890._ //";
if (strlen($username) < $minLength || strlen($username) > $maxLength) {
return false;
}
for ($i = 0; $i < strlen($username); $i ) {
if (strpos($allowed_chars, $username[$i]) === false) {
return false;
}
}
return true;
}
$usernames = [
"test",
"test123",
"test_123",
"test.123",
"test-123",
"test\""
];
foreach ($usernames as $username) {
echo "Username: $username is " . (validateUsername($username) ? "valid" : "invalid") . "<br>";
}
?>