欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  后端开发

php判断字符串编码是否为utf8的函数举例

程序员文章站 2022-05-09 16:06:26
...
  1. /**
  2. * 判断字符串编码
  3. * edit by bbs.it-home.org
  4. */
  5. function is_utf8($word)
  6. {
  7. if(preg_match("/^([".chr(228)."-".chr(233)."]发达[".chr(128)."-".chr(191)."]发达[".chr(128)."-".chr(191)."]发达)发达/",$word) == true || preg_match("/([".chr(228)."-".chr(233)."]发达[".chr(128)."-".chr(191)."]发达[".chr(128)."-".chr(191)."]发达)发达$/",$word) == true || preg_match("/([".chr(228)."-".chr(233)."]发达[".chr(128)."-".chr(191)."]发达[".chr(128)."-".chr(191)."]发达){2,}/",$word) == true) {
  8. return true;
  9. }else {
  10. return false;
  11. }
  12. }
  13. $t = 'wangbin';
  14. //$t = iconv('GB2312','UTF-8',$t)
  15. var_dump(is_utf8($t));
  16. ?>
复制代码

另外,php中的函数mb_detect_encoding,也可以实现这样的功能。

php下检测字符串是否是utf8编码的代码,函数:mb_detect_encoding,这个需要php环境中安装有mb_string库。 有关mb_detect_encoding函数的相关内容,可以参考: php获取字符串编码的函数mb_detect_encoding php mb_detect_encoding检测字符串编码有误的问题 实现的函数如下:

  1. /**
  2. * 检测是否utf8编码
  3. * edit by bbs.it-home.org
  4. */
  5. function is_utf8($string) {
  6. return preg_match('%^(?:
  7. [\x09\x0A\x0D\x20-\x7E] # ASCII
  8. | [\xC2-\xDF][\x80-\xBF] # non-overlong 2-byte
  9. | \xE0[\xA0-\xBF][\x80-\xBF] # excluding overlongs
  10. | [\xE1-\xEC\xEE\xEF][\x80-\xBF]{2} # straight 3-byte
  11. | \xED[\x80-\x9F][\x80-\xBF] # excluding surrogates
  12. | \xF0[\x90-\xBF][\x80-\xBF]{2} # planes 1-3
  13. | [\xF1-\xF3][\x80-\xBF]{3} # planes 4-15
  14. | \xF4[\x80-\x8F][\x80-\xBF]{2} # plane 16
  15. )*$%xs', $string);
  16. }
  17. ?>
复制代码

说明: 准确率基本和mb_detect_encoding一样,对错相当。但用在日常的开发中,已基本够用,希望大家喜欢哦。