且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用正则表达式检查字符串中的非法字符

更新时间:2023-02-21 11:03:07

您的代码会检查第一个字符是否无效.要检查是否存在任何无效字符,请否定您的字符类而不是函数返回并删除锚点:

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;
}

当然,您也可以将其缩短为 /[^-\w]/(单词"字符是字母、数字和下划线),甚至只是 /\W/ 如果你不想允许破折号.

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.