用 PHP实现中文字符串的截取
发布时间:2023-03-07 13:45:01 所属栏目:教程 来源:
导读:<?PHP
@header('Content-type: text/html; charset=UTF-8');
$arr = "sa撒的发dfa多少sfd看sdf得12上24飞452机.@$#^辣^&%椒粉b";
/************************************************************
@header('Content-type: text/html; charset=UTF-8');
$arr = "sa撒的发dfa多少sfd看sdf得12上24飞452机.@$#^辣^&%椒粉b";
/************************************************************
<?PHP @header('Content-type: text/html; charset=UTF-8'); $arr = "sa撒的发dfa多少sfd看sdf得12上24飞452机.@$#^辣^&%椒粉b"; /****************************************************************** * 程序一:PHP截取中文字符串方法 * 截取中文字符串时出现乱码 ****************************************************************/ function msubstr($str,$start,$len) { $tmpstr = ""; $strlen = $start + $len; for($i = 0; $i < $strlen; $i++) { if(ord(substr($str,$i,1)) > 0xa0) { $tmpstr .= substr($str,2); $i++; } else $tmpstr .= substr($str,1); } return $tmpstr; } echo msubstr($arr,15); echo "<br><hr><br>"; /****************************************************************** * PHP截取UTF-8字符串,解决半字符问题。 * 英文、数字(半角)为1字节(8位),中文(全角)为3字节 * @return 取出的字符串,当$len小于等于0时,会返回整个字符串 * @param $str 源字符串 * $len 左边的子串的长度 ****************************************************************/ function utf_substr($str,$len) { for($i=0;$i<$len;$i++) { $temp_str=substr($str,1); if(ord($temp_str) > 127) { $i++; if($i<$len) { $new_str[]=substr($str,3); $str=substr($str,3); } } else { $new_str[]=substr($str,1); $str=substr($str,1); } } return join($new_str); } echo utf_substr($arr,39); echo "<br><hr><br>"; /****************************************************************** * PHP截取UTF-8字符串,解决半字符问题。 * 截取utf-8字符串,截取后,用 ...代替被截取的部分 * $length 左边的子串的长度 ****************************************************************/ function cutstr($string,$length) { preg_match_all("/[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]/",$string,$info); for($i=0; $i<count($info[0]); $i++) { $wordscut .= $info[0][$i]; $j = ord($info[0][$i]) > 127 ? $j + 2 : $j + 1; if ($j > $length - 3) { return $wordscut." ..."; } } return join('',$info[0]); } echo cutstr($arr,14); echo "<br><hr><br>"; ?> (编辑:汽车网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |