blah
blah

Reputation: 239

Validate that string contains only numbers, letters, and underscores

How do you check if a string contains invalid characters?

I want to restrict each user's username with PHP to having numbers, letters, and underscores.

Upvotes: 2

Views: 8878

Answers (2)

user353297
user353297

Reputation: 736

Try:

<?php
function IsSafe($string)
{
    if(preg_match('/[^a-zA-Z0-9_]/', $string) == 0)
    {
        return true;
    }
    else
    {
        return false;
    }
}
?>

Upvotes: 7

Dean Harding
Dean Harding

Reputation: 72678

You can use a regular expression:

if (preg_match("^[0-9A-Za-z_]+$", username) == 0) {
    echo "<p>Invalid username</p>";
}

Upvotes: 10

Related Questions