使用正则表达式检查字符串中的非法字符 [英] Checking String for illegal characters using regular expression

查看:151
本文介绍了使用正则表达式检查字符串中的非法字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在 PHP 中使用以下正则表达式检查任何非法字符.本质上,我只想允许字母数字和下划线 (_).不幸的是,以下代码似乎无法正常工作.如果字符串 $username 中有任何非法字符,它应该返回 true.但是,它仍然允许字符串中的任何字符.知道正则表达式有什么问题吗?

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

提前致谢.

推荐答案

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

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.

这篇关于使用正则表达式检查字符串中的非法字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆