PHP Regex String Allow Chinese Word, alphanumeric & few special characters -


hi can in below code validation in username text field. allow chinese word, alphanumeric , special characters "_" , "-" only.

added: i'm trying create validation username text field, allow chinese word, alphanumeric & "-" & "_" . i'm trying figure out regex below, not work expected. can hep.

if (preg_match("/[~`!@#$%^&*()+={}\[\]|\\:;\"'<>,.?\/]/", "小明@ah meng")) {   echo "invalid"; } else {   echo "valid"; } 

the han unification comprehends multiple code points cjk. since pcre allows unicode categories \p token, can match chinese characters \p{han}.

code:

<?php     $str = "小明ahmeng";      $regex = '/^[-_a-za-z0-9\p{han}]+$/u';   // notice spaces not included      if (preg_match( $regex, $str)) {         echo "valid";     } else {         echo "invalid";     } ?> 

demo

also, don't forget set /u modifier when you're working utf-8 encoded strings.


Comments

Popular posts from this blog

java - Date formats difference between yyyy-MM-dd'T'HH:mm:ss and yyyy-MM-dd'T'HH:mm:ssXXX -

c# - Get rid of xmlns attribute when adding node to existing xml -