PHP preg_match - only allow alphanumeric strings and - _ characters

后端 未结 5 2057
醉话见心
醉话见心 2020-12-04 15:50

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\"         


        
5条回答
  •  长情又很酷
    2020-12-04 16:13

    Here is one equivalent of the accepted answer for the UTF-8 world.

    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{N} => matches any kind of numeric character
    • _- => matches underscore and hyphen
    • + => Quantifier — Matches between one to unlimited times (greedy)
    • /u => Unicode modifier. Pattern strings are treated as UTF-16. Also 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.

提交回复
热议问题