繁体   English   中英

PHP preg_match - 仅允许使用字母数字字符串和__字符

[英]PHP preg_match - only allow alphanumeric strings and - _ characters

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

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

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

码:

if(preg_match('/[^a-z_\-0-9]/i', $string))
{
  echo "not valid string";
}

说明:

  • [] =>字符类定义
  • ^ =>否定班级
  • az =>从'a'到'z'的字符
  • _ =>下划线
  • - =>连字符' - '(你需要逃脱它)
  • 0-9 =>数字(从零到九)

正则表达式末尾的'i'修饰符用于'不区分大小写',如果你没有说你需要在代码中添加大写字符之前做AZ

if(!preg_match('/^[\w-]+$/', $string1)) {
   echo "String 1 not acceptable acceptable";
   // String2 acceptable
}

这是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\\-可能是最好的,但这里只是另一种选择
使用[:alnum:]

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

demo1 | DEMO2

这是一个使用str_word_count()的时髦非正则表达式方法:

if($string===str_word_count($string,1,'-_0...9')[0]){
//                                     ^^^^^^^--- characters to allow, see documentation 
    echo "pass";
}else{
    echo "fail";
}

查看演示链接 ,其中显示了不同输入如何产生不同的输出数组。

为什么要使用正则表达式? PHP有一些内置的功能来做到这一点

<?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))将检查valid_symbols

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM