Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/265.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
PHP preg_match-仅允许字母数字字符串和-_字符_Php_Regex_Preg Match - Fatal编程技术网

PHP preg_match-仅允许字母数字字符串和-_字符

PHP preg_match-仅允许字母数字字符串和-_字符,php,regex,preg-match,Php,Regex,Preg Match,我需要正则表达式来检查字符串是否只包含数字、字母、连字符或下划线 $string1 = "This is a string*"; $string2 = "this_is-a-string"; if(preg_match('******', $string1){ echo "String 1 not acceptable acceptable"; // String2 acceptable } 代码: 说明: []=>字符类定义 ^=>否定该类 a-z=>字符从“a”到“z” _

我需要正则表达式来检查字符串是否只包含数字、字母、连字符或下划线

$string1 = "This is a string*";
$string2 = "this_is-a-string";

if(preg_match('******', $string1){
   echo "String 1 not acceptable acceptable";
   // String2 acceptable
}
代码:

说明:

  • []=>字符类定义
  • ^=>否定该类
  • a-z=>字符从“a”到“z”
  • _=>下划线
  • -=>连字符'-'(需要对其进行转义)
  • 0-9=>数字(从零到九)

正则表达式末尾的“i”修饰符表示“不区分大小写”,如果您没有在代码中添加大写字符,那么在执行A-Z之前,为什么要使用正则表达式?PHP有一些内置的功能来实现这一点

if(!preg_match('/^[\w-]+$/', $string1)) {
   echo "String 1 not acceptable acceptable";
   // String2 acceptable
}
<?php
    $valid_symbols = array('-', '_');
    $string1 = "This is a string*";
    $string2 = "this_is-a-string";

    if(preg_match('/\s/',$string1) || !ctype_alnum(str_replace($valid_symbols, '', $string1))) {
        echo "String 1 not acceptable acceptable";
    }
?>

preg_match('/\s/',$username)
将检查空格


!ctype_alnum(str_replace($valid_symbols,,$string1))
将检查有效的_symbols

\w\-
可能是最好的,但这里只是另一种选择
使用
[:alnum::

if(!preg_match("/[^[:alnum:]\-_]/",$str)) echo "valid";

|

这里有一个相当于UTF-8世界公认答案的答案

if (!preg_match('/^[\p{L}\p{N}_-]+$/u', $string)){
  //Disallowed Character In $string
}
说明:

  • []=>字符类定义
  • p{L}=>匹配来自任何语言的任何种类的字母字符
  • p{N}=>匹配任何类型的数字字符
  • _-=>匹配下划线和连字符
  • +=>量词-一到无限次之间的匹配(贪婪)
  • /u=>Unicode修饰符。模式字符串被视为UTF-16。阿尔索 使转义序列与unicode字符匹配

请注意,如果连字符是类定义中的最后一个字符,则不需要对其进行转义。如果破折号出现在类定义的其他地方,则需要对其进行转义,因为它将被视为范围字符而不是连字符。

您能解释一下什么是
w
?我不太理解这个字母数字字符加上“”,即[A-Za-z0-9]@matino:你需要锚定你的正则表达式,除非它匹配
A;b
如果有人仍然在寻找答案
\w
包括
[a-z a-z 0-9]
,这就是为什么
\w\-
,所以它将是
[a-zA-Z0-9-
这允许使用诸如你好" 无论如何,要检查这一点?@wlin您需要将
\x{4e00}-\x{9fa5}
添加到charecter类定义中,还要添加
u
修饰符,将字符串和模式视为UTF-8。它看起来像这样
/[^a-z \-0-9\x{4e00}-\x{9fa5}]/ui
您可以在此处进行测试:@SERPRO您的共享链接不起作用。@Kamlesh是的,该域不再起作用,但这只是一个示例,您可以尝试在该URL中使用正则表达式,但您仍然使用正则表达式,因此您的解决方案毫无意义在您描述的字符类中何时需要转义连字符时不完全正确。如果连字符n位于字符类的开头或紧跟在字符范围之后(如
[0-9-a.]
),将按字面处理。此解决方案不适用于土耳其语字符。谢谢。
if (!preg_match('/^[\p{L}\p{N}_-]+$/u', $string)){
  //Disallowed Character In $string
}