php method to determine whether a string is Chinese or numeric: 1. Judge by "if (preg_match("/^[\x7f-\xff] $/", $str)){...}" Whether it is Chinese; 2. Use the "function checkStr($str){...}" method to determine the string type.
The operating environment of this tutorial: Windows 10 system, PHP version 8.1, DELL G3 computer
How to determine whether a string is Chinese in php Or numbers?
php Determine whether it is Chinese/English/numeric sample code
The judgment of Chinese, English, and numeric is also often used in projects, as follows A good example, you can refer to it, it may be helpful
The code is as follows:
$str='asb天水市12'; if (preg_match("/^[\x7f-\xff]+$/", $str)){ echo '全部是汉字'; }else { echo '不全是汉字'; } /** PHP自带的判断是否是中文, eregi('[^\x00-\x7F]', $str ) //中文 eregi('[0-9]', $str) //数字 eregi('[a-zA-Z]', $str)//英文 */ if (eregi('[^\x00-\x7F]', $str) || eregi('[0-9]', $str) || eregi('[a-zA-Z]', $str)){ echo '你输入的为中英文数字的并合体哦!'.'<br>'; echo "长度:".strlen($str); } / ** 下面这两个方法是用来判断是否是英文汉字和数字组成的字符串, 或者全部是中文组成的字符串 用的变量$str还是本文开头的变量 */ if (preg_match_all("/^([\x81-\xfe][\x40-\xfe])+$/", $str, $match)) { echo '全部是汉字'; } else { echo '不全是汉字'; } if (preg_match("/([\x81-\xfe][\x40-\xfe])/", $str, $match)) { echo '含有汉字'; } else { echo '不含有汉字'; } /** 此为js方法,判断了一个汉字占两个字节,一个中文或数字占一个,使用编码为UTF-8 */ <script> var leng = {}; var value = document.forms[0].name.value; jmz.GetLength = function(str) { var realLength = 0, len = str.length, charCode = -1; for (var i = 0; i < len; i++) { charCode = str.charCodeAt(i); if (charCode >= 0 && charCode <= 128) realLength += 1; else realLength +=2; } return realLength; }; alert(leng.GetLength(value)) </script> function checkStr($str){ $output=''; $a=ereg('['.chr(0xa1).'-'.chr(0xff).']', $str); $b=ereg('[0-9]', $str); $c=ereg('[a-zA-Z]', $str); if($a && $b && $c){ $output='汉字数字英文的混合字符串';} elseif($a && $b && !$c){ $output='汉字数字的混合字符串';} elseif($a && !$b && $c){ $output='汉字英文的混合字符串';} elseif(!$a && $b && $c){ $output='数字英文的混合字符串';} elseif($a && !$b && !$c){ $output='纯汉字';} elseif(!$a && $b && !$c){ $output='纯数字';} elseif(!$a && !$b && $c){ $output='纯英文';} return $output; } echo checkStr('5爱u');
Recommended learning: "PHP Video Tutorial"
The above is the detailed content of How to determine whether a string is Chinese or numeric in php. For more information, please follow other related articles on the PHP Chinese website!