Introduction to the method of php regular matching Chinese characters

  • 2020-05-30 19:45:40
  • OfStack

php regular matching Chinese characters!

/^[\x{4e00}-\x{9fa5}]+$/u

The above regular expression is the regular expression of matching Chinese characters that troubles many php programmers

You may think it is very simple, in fact, different coding, different programming languages, there are some subtle differences, a little bit not to pay attention to you can not get the right results.

Here is an example of utf-8 encoding:
$str = "Chinese characters ";
if (preg_match("/^[\x{4e00}-\x{9fa5}]+$/u",$str)) {
print(" this string is all in Chinese ");
} else {
print(" the string is not all Chinese ");
}

The following example contains the example of gbk, gb2312:

< ?php
$action = trim($_GET['action']);
if($action == "sub")
{
$str = $_POST['dir'];
/ / if (! preg_match("/^[".chr(0xa1)."-".chr(0xff)." A-Za-z0-9_]+$/",$str)) //GB2312 Chinese alphanumeric underlined regular expression
if (! preg_match("/^[\x{4e00}-\x{9fa5} A-Za-z0-9_]+$/u",$str)) // UTF-8 Chinese alphanumerics underlined regular expressions
{
echo " < font color=red > The [".$str."] you entered contains illegal characters < /font > ";
}
else
{
echo " < font color=green > The [".$str."] you entered is completely legal, via! < /font > ";
}
}
? >
< form method="POST" action="?action=sub" >
Input characters (digits, letters, Chinese characters, underline):
< input type="text" name="dir" value="" >
< input type="submit" value=" submit" >
< /form >


Related articles: