|
本帖最后由 追影 于 2018-11-20 17:41 编辑
- //中英文混合转英文宽度
- function strWidthMix($str, $charset = 'utf-8') {
- if ($charset == 'utf-8')
- $str = mb_convert_encoding($str, "GBK", "UTF-8");
- $num = strlen ( $str );
- $str_num = 0;
- for($i = 0; $i < $num; $i ++) {
- if (ord ( substr ( $str, $i + 1, 1 ) ) > 127) {
- $str_num += 2;
- $i ++;
- }else{
- $str_num += 1;
- }
- }
- return $str_num;
- }
- //切去固定的混合宽度
- function strCutMix($str,$long=76,$charset = 'utf-8'){
- $num = strlen($str);
- $width = $this->strWidthMix($str);
- if($width <= $long){return array(0=>$str);}
- if ($charset == 'utf-8') {
- $str = mb_convert_encoding($str, "GBK", "UTF-8");
- }
- $temp_long = 0;
- $temp_str = '';
- $ret = array();
- for($i = 0; $i < $num; $i++) {
- //繁体
- if (ord ( substr ( $str, $i, 1 ) ) >= 224) {
- $temp_long += 2;
- $temp_str .= substr($str, $i, 3);
- if($temp_long>=$long && $temp_str != ''){
- $ret[] = $charset == 'utf-8'?mb_convert_encoding($temp_str, "UTF-8","GBK"):$temp_str;
- $temp_str='';
- $temp_long = 0;
- }
- $i += 2;
- }else if (ord ( substr ( $str, $i, 1 ) ) >=127) {
- //简体
- $temp_long += 2;
- $temp_str .= substr($str, $i, 2);
- if($temp_long >= $long && $temp_str != ''){
- $ret[] = $charset == 'utf-8'?mb_convert_encoding($temp_str, "UTF-8","GBK"):$temp_str;
- $temp_str='';
- $temp_long = 0;
- }
- $i += 1;
- }else{
- //英文
- $temp_long +=1;
- $temp_str .= substr($str, $i, 1);
- if($temp_long>=$long && $temp_str != ''){
- $ret[] = $charset == 'utf-8'?mb_convert_encoding($temp_str, "UTF-8","GBK"):$temp_str;
- $temp_str='';
- $temp_long = 0;
- }
- }
- }
- if($temp_str !=''){$ret[] = $charset == 'utf-8'?mb_convert_encoding($temp_str, "UTF-8","GBK"):$temp_str;}
- return $ret;
- }
复制代码
将上面代码放置任意helper调用即可 |
|