3v4l.org

run code in 300+ PHP versions simultaneously
<?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 GBsubstr($string, $start, $length) { if(strlen($string)>$length){ $str=null; $len=$start+$length; for($i=$start;$i<$len;$i++){ if(ord(substr($string,$i,1))>0xa0){ $str.=substr($string,$i,2); $i++; }else{ $str.=substr($string,$i,1); } } return $str.'...'; }else{ return $string; } } $a = '测试这是一个测试'; //$a = 'xxxxbbbbbnnn'; $b = GBsubstr($a,0,5); var_dump($b); ?>
Output for 8.1.0 - 8.1.28, 8.2.0 - 8.2.18, 8.3.0 - 8.3.6
Deprecated: Optional parameter $start declared before required parameter $length is implicitly treated as a required parameter in /in/lNXl7 on line 3 string(8) "测�..."
Output for 8.0.0 - 8.0.30
Deprecated: Required parameter $length follows optional parameter $start in /in/lNXl7 on line 3 string(8) "测�..."
Output for 4.3.0 - 4.3.11, 4.4.0 - 4.4.9, 5.0.0 - 5.0.5, 5.1.0 - 5.1.6, 5.2.0 - 5.2.17, 5.3.0 - 5.3.29, 5.4.0 - 5.4.45, 5.5.0 - 5.5.36, 5.6.0 - 5.6.28, 7.0.0 - 7.0.20, 7.1.0 - 7.1.33, 7.2.0 - 7.2.33, 7.3.0 - 7.3.33, 7.4.0 - 7.4.33
string(8) "测�..."

preferences:
318 ms | 404 KiB | 375 Q