*#$"; if (preg_match("/^[0-9a-z-A-Z-_@ !]*/", $username)) { echo "true"; } els...">

Why is this PHP not being checked?

<?php
$username = "@#*(#(*#($&*#$";

if (preg_match("/^[0-9a-z-A-Z-_@ !]*/", $username)) 
{
   echo "true";
} else {
   echo "false";
}
?>

      

+2


source to share


6 answers


Two things:

  • -

    inside [...]

    is a special character indicating a range and must be escaped; and

  • \w

    is a shortcut for [A-Za-z0-9_]

    . You should use it (although not using it is technically not a problem here).



So:

if (preg_match('/^[\w\-@ !]*/', $username))

      

+1


source


As written, this regex will match zero or more of the listed characters at the beginning of the line, which means it will always succeed, no matter what is in the input string. If you want to restrict the input to only those characters, you need to bind it at both ends:

'/^[0-9a-zA-Z_@ !-]*$/'

      

But keep in mind that it will still match an empty string; if you want to prevent this, you should change *

to +

.



Notice how I removed two from the hyphen and added one to the end of the character class. Since hyphens have a special meaning in character classes, you must make it as clear as possible if you want you to match literally. You do this either with a backslash or by placing it in the first or last position.

The "extra" hyphens in your regex were actually treated as literal hyphens because they couldn't form the ranges where they were — in each case, the previous character was already part of the range. However, don't rely on this behavior; not all regex flavors are as simple as PHP. And of course this looks like a bug to anyone reading your code.

+2


source


There is a problem here: Z-_

because there is -

, it means "characters from z

to _

. Correct regexp /^[0-9a-zA-Z\-_@ !]*/

, backflush -

.

+1


source


The problem is with -

regex usage . Also, you may need the regex to match the entire line, so you must put the end of the line marker as well.

if(preg_match('/^[0-9a-zA-Z\-_@ !]*$/', $username)

      

+1


source


You should probably have placed your caret inside square brackets like so

if (preg_match("/[^0-9a-z-A-Z-_@ !]*/", $username)) 

      

0


source


You need to specify the end of the line. Otherwise, any repetition of the character class with zero time (resulting in a regex equivalent ^

) will match any string:

/^[0-9a-z-A-Z-_@ !]*$/

      

0


source







All Articles