Home > Article > Backend Development > Can php determine whether a string is Chinese?
Can judge. Judgment method: 1. Use the preg_match() function with regular rules to determine whether it is all Chinese, the syntax is "!preg_match("/[^\x80-\xff]/i",$str)"; 2. Use the preg_match() function Use regular rules to determine whether it contains Chinese characters, using the syntax "preg_match("/[\x7f-\xff]/", $str)" or "preg_match('/[^\x00-\x80]/',$str)".
The operating environment of this tutorial: windows7 system, PHP version 8.1, DELL G3 computer
php can determine whether the string is Chinese, mainly It is determined by using regular Chinese matching.
The judgment can be divided into two situations:
The string is all Chinese characters
The string contains Chinese
Case 1: Judgment is all Chinese
Method: preg_match() function regular expression "/[^\x80-\xff]/i
”
<?php header('content-type:text/html;charset=utf-8'); $str = "12hello13"; $str="'324是"; if(!preg_match("/[^\x80-\xff]/i",$str)){ echo "全是中文,是中文字符串"; }else{ echo "不是中文字符串"; } ?>
##Case 2: Determine to contain Chinese
Method 1: preg_match() function regular expression "/[\x7f-\xff]/"
<?php header('content-type:text/html;charset=utf-8'); $str = "中文"; if (preg_match("/[\x7f-\xff]/", $str)) { echo "含有中文"; }else{ echo "没有中文"; } ?>Method 2: preg_match ()Function regular expression "
/[^\x00-\x80]/"
<?php header('content-type:text/html;charset=utf-8'); $str = "1234"; $pattern = '/[^\x00-\x80]/'; if(preg_match($pattern,$str)){ echo "含有中文"; }else{ echo "没有中文"; } ?>##Function description: preg_match()
The preg_match() function in PHP can search and match strings based on regular expressions. The syntax format of the function is as follows:
preg_match($pattern,$subject [, &$matches [, $flags = 0 [, $offset = 0 ]]])
Recommended learning: "
PHP Video TutorialThe above is the detailed content of Can php determine whether a string is Chinese?. For more information, please follow other related articles on the PHP Chinese website!