Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking String for illegal characters using regular expression

Tags:

regex

php

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 follow piece of code does not seem to work properly. It should return true if there is any illegal character in the string $username. However, it still allows any character in the string. Any idea what is wrong with the regular expression?

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

Thanks in advance.

like image 283
kjloh Avatar asked Aug 21 '26 04:08

kjloh


1 Answers

Your code checks to see if the first character is not valid. To check to see if any invalid characters exist, negate your character class rather than the function return and remove the anchor:

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

You could also, of course, shorten it to /[^-\w]/ ("word" characters are letters, numbers, and the underscore), or even just /\W/ if you don't want to allow dashes.

like image 145
Ben Blank Avatar answered Aug 22 '26 21:08

Ben Blank



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!