PHP preg_match - 只允许字母数字字符串和 - _ 字符
我需要正则表达式来检查字符串是否只包含数字、字母、连字符或下划线
$string1 = "This is a string*";
$string2 = "this_is-a-string";
if(preg_match('******', $string1){
echo "String 1 not acceptable acceptable";
// String2 acceptable
}
I need the regex to check if a string only contains numbers, letters, hyphens or underscore
$string1 = "This is a string*";
$string2 = "this_is-a-string";
if(preg_match('******', $string1){
echo "String 1 not acceptable acceptable";
// String2 acceptable
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
代码:
解释:
正则表达式末尾的“i”修饰符用于“不区分大小写”,如果您不输入,则需要在执行 AZ 之前在代码中添加大写字符
Code:
Explanation:
The 'i' modifier at the end of the regex is for 'case-insensitive' if you don't put that you will need to add the upper case characters in the code before by doing A-Z
这是 UTF-8 世界公认的答案的一个等价物。
解释:
导致转义序列匹配 unicode 字符
请注意,如果连字符是类定义中的最后一个字符,则它不需要转义。如果破折号出现在类定义中的其他位置,则它需要转义,因为它将被视为范围字符而不是连字符。
Here is one equivalent of the accepted answer for the UTF-8 world.
Explanation:
causes escape sequences to match unicode characters
Note, that if the hyphen is the last character in the class definition it does not need to be escaped. If the dash appears elsewhere in the class definition it needs to be escaped, as it will be seen as a range character rather then a hyphen.
\w\-
可能是最好的,但这里只是另一种选择使用
[:alnum:]
demo1 | 演示2
\w\-
is probably the best but here just another alternativeUse
[:alnum:]
demo1 | demo2
为什么要使用正则表达式? PHP 有一些内置功能可以执行
preg_match('/\s/',$username)
检查空格!ctype_alnum(str_replace($valid_symbols, '', $string1) )
将检查 valid_symbolsWhy to use regex? PHP has some built in functionality to do that
preg_match('/\s/',$username)
will check for blank space!ctype_alnum(str_replace($valid_symbols, '', $string1))
will check for valid_symbols