Joe Scotto
Joe Scotto

Reputation: 10877

Compare username to regular expression with PHP

I've never used regular expressions before and did some research on how to allow my username field only alphanumeric characters, dashes, dots, and underscores. I have the following expression but it doesn't seem to be working.

$string = "Joe_Scotto";

if (!preg_match('[a-zA-Z0-9_-.]', $string)) {
    echo "Does not match Regex";
} else {
    echo "Matches";
}

I want the statement to return true if it is following the "guidelines" and false if the username contains something other than what I specified it should contain. Any help would be great. Thanks!

Upvotes: 1

Views: 92

Answers (3)

paranoid
paranoid

Reputation: 7105

Try this

$string = "Joe_Scotto";

if (!preg_match('/^[A-Za-z0-9_.]+$/', $string)) {
    echo "Does not match Regex";
} else {
    echo "Matches";
}

Upvotes: 4

ul90
ul90

Reputation: 787

You match only a single character. Try this:

$string = "Joe_Scotto";

if (!preg_match('/^[a-zA-Z0-9_.-]+$/', $string)) {
    echo "Does not match Regex";
} else {
    echo "Matches";
}

The + sign says: match 1 or more characters defined directly before the + (* is the same but matches 0 or more characters). Also the separators '/' (or any other separator characters) are required. And in character classes, it is better to place the - sign to the end, else it could be misinterpreted as range from _ to . And add ^ at the beginning (this means: match from the beginning of the input) and $ to the end (this means: match to the end of the input). Else, also a part of the string would match.

Upvotes: 3

user4962466
user4962466

Reputation:

You should use something like that http://www.phpliveregex.com/p/ern

$string = 'John_Buss';

if (preg_match('/[A-z0-9_\-.]+/', $string)) {
    return true;
} else {
    return false;
}

Make sure to add / delimiter character at the start and the end of your regex

Make sure to use \ escape character before -

Make sure to add + character quantifier

Upvotes: 1

Related Questions