简体   繁体   English

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

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

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
}

Code: 码:

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

Explanation: 说明:

  • [] => character class definition [] =>字符类定义
  • ^ => negate the class ^ =>否定班级
  • az => chars from 'a' to 'z' az =>从'a'到'z'的字符
  • _ => underscore _ =>下划线
  • - => hyphen '-' (You need to escape it) - =>连字符' - '(你需要逃脱它)
  • 0-9 => numbers (from zero to nine) 0-9 =>数字(从零到九)

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

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

Here is one equivalent of the accepted answer for the UTF-8 world. 这是UTF-8世界接受的答案的一个等价物。

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

Explanation: 说明:

  • [] => character class definition [] =>字符类定义
  • p{L} => matches any kind of letter character from any language p {L} =>匹配任何语言的任何字母字符
  • p{N} => matches any kind of numeric character p {N} =>匹配任何类型的数字字符
  • _- => matches underscore and hyphen _- =>匹配下划线和连字符
  • + => Quantifier — Matches between one to unlimited times (greedy) + =>量词 - 在一到无限次之间匹配(贪婪)
  • /u => Unicode modifier. / u => Unicode修饰符。 Pattern strings are treated as UTF-16. 模式字符串被视为UTF-16。 Also causes escape sequences to match unicode characters 还导致转义序列匹配unicode字符

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\\- is probably the best but here just another alternative \\w\\-可能是最好的,但这里只是另一种选择
Use [:alnum:] 使用[:alnum:]

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

demo1 | demo1 | demo2 DEMO2

Here is a funky non-regex method using str_word_count() : 这是一个使用str_word_count()的时髦非正则表达式方法:

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

View the Demo Link where I show how different inputs result in different output arrays. 查看演示链接 ,其中显示了不同输入如何产生不同的输出数组。

Why to use regex? 为什么要使用正则表达式? PHP has some built in functionality to do that 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) will check for blank space preg_match('/\\s/',$username)将检查空格

!ctype_alnum(str_replace($valid_symbols, '', $string1)) will check for valid_symbols !ctype_alnum(str_replace($valid_symbols, '', $string1))将检查valid_symbols

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

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