3v4l.org

run code in 150+ php & hhvm versions
Bugs & Features
<?php function msubstr($str, $start=0, $length, $charset="utf-8", $suffix=true) { if($suffix) $suffixStr = "…"; else $suffixStr = ""; if(function_exists("mb_substr")) return mb_substr($str, $start, $length, $charset).$suffixStr; elseif(function_exists('iconv_substr')) { return iconv_substr($str,$start,$length,$charset).$suffixStr; } $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)); return $slice.$suffixStr; } function u8_title_substr($str, $width = 0, $end = '...', $x3 = 0) { global $CFG; // 全局变量保存 x3 的值 if ($width <= 0 || $width >= strlen($str)) { return $str; } $arr = str_split($str); $len = count($arr); $w = 0; $width *= 10; // 不同字节编码字符宽度系数 $x1 = 11; // ASCII $x2 = 16; $x3 = $x3===0 ? ( $CFG['cf3'] > 0 ? $CFG['cf3']*10 : $x3 = 21 ) : $x3*10; $x4 = $x3; // http://zh.wikipedia.org/zh-cn/UTF8 for ($i = 0; $i < $len; $i++) { if ($w >= $width) { $e = $end; break; } $c = ord($arr[$i]); if ($c <= 127) { $w += $x1; } elseif ($c >= 192 && $c <= 223) { // 2字节头 $w += $x2; $i += 1; } elseif ($c >= 224 && $c <= 239) { // 3字节头 $w += $x3; $i += 2; } elseif ($c >= 240 && $c <= 247) { // 4字节头 $w += $x4; $i += 3; } } return implode('', array_slice($arr, 0, $i) ). $e; } $a = '测试这是一个测试'; //$a = 'xxxxbbbbbnnn'; $b = u8_title_substr($a,0,5,15); var_dump($b); ?>
Output for 4.3.0 - 5.6.28, hhvm-3.10.0 - 3.12.0, 7.0.0 - 7.1.0
string(24) "测试这是一个测试"