Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

PHP Verify if a string dosnt contain anything else except alpha-numeric or characters gived

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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>";
}
?>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading