$foo = "username122";
pre_match('Contain only aplhanumeric string', $foo){
return true;
}
$foo
只包含字母数字没有特殊字符(=\*-[
(ETC)我如何能在一个字符串找到字母数字的
$foo = "username122";
pre_match('Contain only aplhanumeric string', $foo){
return true;
}
$foo
只包含字母数字没有特殊字符(=\*-[
(ETC)我如何能在一个字符串找到字母数字的
使用正则表达式只从开始的字母数字字符匹配结束:
/^[A-Za-z0-9]*$/
例如:
$testRegex = "/^[A-Za-z0-9]*$/";
$testString = "abc123";
if (preg_match($testRegex, $testString)) {
// yes, the string is entirely alphanumeric
} else {
// no, the string is not entirely alphanumeric
}
你的正则表达式是这样的PHP和JavaScript之间不会改变。在JavaScript中它是一个对象,而在PHP这是一个字符串,但该模式仍然是相同的:
/^[a-z0-9]+$/i
其中^
表示字符串的开始和$
表示字符串的结束。接下来,a-z
匹配任何字母,并且0-9
匹配任何数字。 +
指出以前的模式可以重复一次或多次。 i
修饰符使a-z
部分不区分大小写,因此大小写都匹配。
测试在JavaScript:
/^[a-z0-9]+$/i.test("Foo123"); // true
测试在PHP中:
preg_match("/^[a-z0-9]+$/i", "Foo123"); // 1
使用PHP,你必须使用POSIX字符类,如:alnum:
的选项。请注意,这不会在JavaScript工作:
preg_match("/^[[:alnum:]]+$/i", "Foo123"); // 1
实际上,有在PHP测试更简单的方法,使用Ctype functions,特别是ctype_alnum
功能,它会返回一个布尔值,说明是否在所有字符给定的字符串是字母或不:
ctype_alnum("Foo123"); // true
ctype_alnum("Foo!23"); // false
thanx itz工作时,我把$ foo =“username123?* - =” 它给我的欲望错误,但当我给$ foo =“username123?* - = \“ 它不会给我错...... – user1812138
”username123?“的值将会失败,并且'\”'会在JavaScript和PHP中引发问题,除非您的'\'被进一步转义。 – Sampson
if(preg_match('~[^a-z0-9 ]~i', $foo)) {
//DO SOMETHING HERE;
}
添加的标签实际上标签的问题或者你只是想获得一些关注? – hakre