当前位置: 移动技术网 > IT编程>开发语言>PHP > 完美的2个php检测字符串是否是utf-8编码函数分享

完美的2个php检测字符串是否是utf-8编码函数分享

2019年03月20日  | 移动技术网IT编程  | 我要评论

在php开发中有时候会用到转码函数,比如iconv(),mb_convert_encoding()函数,在用函数转码的时候或者解码的时候我们有时候需要先判断当前字符串编码类型,不如是否是utf-8编码,是的话然后进行编码转换等操作。下面是小编整理的目前web开发中网上使用率比较高的、好的php关于utf-8编码的判断函数,代码如下:

function is_utf8($string) //函数一
{
// from http://w3.org/international/questions/qa-forms-utf-8.html
return preg_match(‘%^(?:
[\x09\x0a\x0d\x20-\x7e] # ascii
| [\xc2-\xdf][\x80-\xbf] # non-overlong 2-byte
| \xe0[\xa0-\xbf][\x80-\xbf] # excluding overlongs
| [\xe1-\xec\xee\xef][\x80-\xbf]{2} # straight 3-byte
| \xed[\x80-\x9f][\x80-\xbf] # excluding surrogates
| \xf0[\x90-\xbf][\x80-\xbf]{2} # planes 1-3
| [\xf1-\xf3][\x80-\xbf]{3} # planes 4-15
| \xf4[\x80-\x8f][\x80-\xbf]{2} # plane 16
)*$%xs', $string);
}

function mb_is_utf8($string) //函数二
{
return mb_detect_encoding($string, ‘utf-8′) === ‘utf-8′;
}

mb_detect_encoding()函数是php的一个内置函数,用来判断当前字符串编码类型,此函数有三个参数,第一个参数是要判断的字符串,第二个参数是比较的字符编码列表,可以使字符串,也可以是数组,第三个参数是要求。
希望这两个函数对需要的phper有所帮助。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网