PHP獲取中英文混合字串長度及擷取
阿新 • • 發佈:2019-01-05
1.字串長度
function msubstr($str, $start, $len) {
<?php
function cc_msubstr($str, $start=0, $length, $charset="utf-8", $suffix=true)
PHP獲取中英文混合字串長度的實現程式碼如下,1中文=1位,2英文=1位,可自行修改
[php]- /**
- * PHP獲取字串中英文混合長度
- * @param $str string 字串
- * @param $$charset string 編碼
- * @return 返回長度,1中文=1位,2英文=1位
- */
- function strLength($str,$charset='utf-8'){
- if($charset=='utf-8') $str = iconv('utf-8','gb2312',$str);
- $num = strlen($str);
- $cnNum = 0;
- for($i=0;$i<$num;$i++){
- if(ord(substr($str,$i+1,1))>127){
- $cnNum++;
- $i++;
- }
- }
- $enNum = $num-($cnNum*2);
- $number = ($enNum/2)+$cnNum;
- return ceil($number);
- }
- //測試輸出長度都為15
- $str1 = '測試測試測試測試測試測試測試測';
- $str2 = 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa';
- $str3 = 'aa測試aa測試aa測試aa測試aaaaaa';
- echo strLength($str1,'gb2312');
- echo strLength($str2,'gb2312');
- echo strLength($str3,'gb2312');
2.擷取字串函式
UTF8編碼,在UTF8中,一箇中文字元佔3個位元組
[php]function msubstr($str, $start, $len) {
- $tmpstr = "";
- $strlen = $start + $len;
- for($i = 0; $i < $strlen; $i++){
- if(ord(substr($str, $i, 1)) > 127){
- $tmpstr.=substr($str, $i, 3);
- $i+=2;
- }else
- $tmpstr.= substr($str, $i, 1);
- }
- return $tmpstr;
- }
- echo msubstr("一二三天下致公english",0,10);
GB2312編碼,在gb2312中,一箇中文字元佔2個位元組
[php]<?php
- function msubstr($str, $start, $len) { //ȡ
- $tmpstr = "";
- $strlen = $start + $len;
- if(preg_match('/[/d/s]{2,}/',$str)){$strlen=$strlen-2;}
- for($i = 0; $i < $strlen; $i++) {
- if(ord(substr($str, $i, 1)) > 0xa0) {
- $tmpstr .= substr($str, $i, 2);
- $i++;
- } else
- $tmpstr .= substr($str, $i, 1);
- }
- return $tmpstr;
- }
- ?>
編碼相容性良好的函式
[php]function cc_msubstr($str, $start=0, $length, $charset="utf-8", $suffix=true)
- {
- if(function_exists("mb_substr"))
- return mb_substr($str, $start, $length, $charset);
- elseif(function_exists('iconv_substr')) {
- return iconv_substr($str,$start,$length,$charset);
- }
- $re['utf-8'] = "/[/x01-/x7f]|[/xc2-/xdf][/x80-/xbf]|[/xe0-/xef][/x80-/xbf]{2}|[/xf0-/xff][/x80-/xbf]{3}/";
- $re['gb2312'] = "/[/x01-/x7f]|[/xb0-/xf7][/xa0-/xfe]/";
- $re['gbk'] = "/[/x01-/x7f]|[/x81-/xfe][/x40-/xfe]/";
- $re['big5'] = "/[/x01-/x7f]|[/x81-/xfe]([/x40-/x7e]|/xa1-/xfe])/";
- preg_match_all($re[$charset], $str, $match);
- $slice = join("",array_slice($match[0], $start, $length));
- if($suffix) return $slice."…";
- return $slice;
- }