Validating string for invalid characters using regular expression

I want to check a for any illegal character using the following regular expression in PHP. Essentially, I want to allow only alphanumeric and underscore (_). Unfortunately, the following code fragment does not seem to work properly. It should return true if there is any illegal character in the $ username string. However, it still allows you to use any character in the string. Any idea what is wrong with regex?

if ( !preg_match("/^[-a-z0-9_]/i", $username) )
{
    return true;
}

Thanks in advance.

+1
source share
5 answers

, . , - , , :

if ( preg_match("/[^-a-z0-9_]/i", $username) )
{
    return true;
}

/[^-\w]/ ( "" - , ) /\W/, .

+15

$username - , TRUE

if (preg_match("/^[a-z0-9_]+$/i", $username) )
{
    return true;
}
+2

1 . /^ [- a-z0-9 _] + $/i "+" 1 , "$" -

+1

You also need to bind it at the end, and not just check the first character. Try it instead "/^[-a-z0-9_]*$/i".

+1
source

You do not have a repeater for one. You need a repeater such as +. As far as I can see, without doing it, you check the beginning of the line and one character matching a-zA-Z0-9 and _, but not following the first character.

0
source

Source: https://habr.com/ru/post/1771864/


All Articles