下面我来介绍PHP strlen与mb_strlen判断字符串是纯英文/纯汉字/汉英混合,在php中UTF8每个汉字等于3个长度; GBK每个汉字等于2个长度;
利用以上汉字与英文的差异,我们就可以利用mb_strlen函数与strlen函数分别计算出两组长度数字,然后根据规律进行运算即可判断出字符串的类型了
先讲一下strlen与mb_strlen是求字符串长度的函数
代码如下 | 复制代码 |
//测试时文件的编码方式要是UTF8 $str='中文a字1符'; echo strlen($str).' echo mb_strlen($str,'utf8').' echo mb_strlen($str,'gbk').' echo mb_strlen($str,'gb2312').' ?> |
PHP内置的字符串长度函数strlen无法正确处理中文字符串,它得 到的只是字符串所占的字节数。对于GB2312的中文编码,strlen得到的值是汉字个数的2倍,而对于UTF-8编码的中文,就是3倍的差异了(在 UTF-8编码下,一个汉字占3个字节)。
例
代码如下 | 复制代码 |
/** * PHP判断字符串纯汉字 OR 纯英文 OR 汉英混合 */ function utf8_str($str){ $mb = mb_strlen($str,'utf-8'); $st = strlen($str); if($st==$mb) return '纯英文'; if($st%$mb==0 && $st%3==0) return '纯汉字'; return '汉英混合'; } $str = '琼台博客'; echo '字符串:'.$str.',是'.utf8_str($str).''; ?> |
需要注意的是,mb_strlen并不是PHP核心函数,使用前需要确保在php.ini中加载了php_mbstring.dll,即确保“extension=php_mbstring.dll”这一行存在并且没有被注释掉,否则会出现未定义函 数的问题

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

Zend Studio 13.0.1
Powerful PHP integrated development environment

SublimeText3 English version
Recommended: Win version, supports code prompts!

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool