views:

138

answers:

2

How do you check if a username contains invalid characters?

I want to restrict each users username with PHP to having numbers, letters, and underscores.

+3  A: 

You can use a regular expression:

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

Try:

<?php
function IsSafe($string)
{
    if(preg_match('/[^a-zA-Z0-9_]/', $string) == 0)
    {
        return true;
    }
    else
    {
        return false;
    }
}
?>
you might as well return (preg_match('/[^a-zA-Z0-9_]/', $string) == 0)
Artefacto
@Art Technically `preg_match` returns an int, so there is a minor difference
Michael Mrozek
@Michael Mrozek You need to read my comment again.
Artefacto
@Art Ah, right.
Michael Mrozek