在PHP中截取字符串
轉自 : http://www.focuslib.com/article/php/1244913925.shtml
也可使用 mb_strimwidth 函數,但是中英文都算一個字符,出來后長短還是不一~
代码
function SubString($str, $start=0, $len=0, $code=\’utf-8\’){
if(!is_numeric($len)) return $str;
if($len==0) $len=strlen($str)–$start;
if($code == \’utf-8\’){
$pa = “/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|\xe0[\xa0-\xbf][\x80-\xbf]|[\xe1-\xef][\x80-\xbf][\x80-\xbf]|\xf0[\x90-\xbf][\x80-\xbf][\x80-\xbf]|[\xf1-\xf7][\x80-\xbf][\x80-\xbf][\x80-\xbf]/“;
preg_match_all($pa,$str,$tstr);
if(count($tstr[0]) – $start > $len) return join(\’\’, array_slice($tstr[0], $start, $len)) . ““;
return join(\’\’,array_slice($tstr[0], $start, $len));
}else{
$start = $start * 2;
$len = $len * 2;
$sl = strlen($str);
$tmpstr = \’\’;
for($i = 0; $i < $sl; $i++){
if($i >= $start && $i < ($start + $len)){
if(ord(substr($str, $i, 1)) > 129){
$tmpstr .= substr($str, $i, 2);
}else{
$tmpstr .= substr($str, $i, 1);
}
}
if(ord(substr($str, $i, 1)) > 129) $i++;
}
if(strlen($tmpstr) < $sl) $tmpstr .= \’\’;
return $tmpstr;
}
}
if(!is_numeric($len)) return $str;
if($len==0) $len=strlen($str)–$start;
if($code == \’utf-8\’){
$pa = “/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|\xe0[\xa0-\xbf][\x80-\xbf]|[\xe1-\xef][\x80-\xbf][\x80-\xbf]|\xf0[\x90-\xbf][\x80-\xbf][\x80-\xbf]|[\xf1-\xf7][\x80-\xbf][\x80-\xbf][\x80-\xbf]/“;
preg_match_all($pa,$str,$tstr);
if(count($tstr[0]) – $start > $len) return join(\’\’, array_slice($tstr[0], $start, $len)) . ““;
return join(\’\’,array_slice($tstr[0], $start, $len));
}else{
$start = $start * 2;
$len = $len * 2;
$sl = strlen($str);
$tmpstr = \’\’;
for($i = 0; $i < $sl; $i++){
if($i >= $start && $i < ($start + $len)){
if(ord(substr($str, $i, 1)) > 129){
$tmpstr .= substr($str, $i, 2);
}else{
$tmpstr .= substr($str, $i, 1);
}
}
if(ord(substr($str, $i, 1)) > 129) $i++;
}
if(strlen($tmpstr) < $sl) $tmpstr .= \’\’;
return $tmpstr;
}
}
版权声明:本文为abinxm原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。