Checking String for illegal characters using regular expression

后端 未结 5 1720
猫巷女王i
猫巷女王i 2021-01-25 21:02

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

相关标签:
5条回答
  • 2021-01-25 21:37

    If $username only has alphanumeric and underscore it will return TRUE

    if (preg_match("/^[a-z0-9_]+$/i", $username) )
    {
        return true;
    }
    
    0 讨论(0)
  • 2021-01-25 21:38

    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.

    0 讨论(0)
  • 2021-01-25 21:57

    Your expression matches only 1 character. Try /^[-a-z0-9_]+$/i the '+' matches more then 1 character and the '$' is the end of line anchor

    0 讨论(0)
  • 2021-01-25 22:00

    You have no repeater for one. You need a repeater such as +. As far as I can see without executing it, you check start of line and one character matching a-zA-Z0-9 and _ but nothing following that first character.

    0 讨论(0)
  • 2021-01-25 22:01

    You need to anchor it at the end too, instead of just checking the first character. Try "/^[-a-z0-9_]*$/i" instead.

    0 讨论(0)
提交回复
热议问题