您的位置:首页 > 编程语言 > PHP开发

PHP截取中文字符串方法总结

2016-09-25 17:49 666 查看
<?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, $i, 2);
$i++;
} else
$tmpstr .= substr($str, $i, 1);
}
return $tmpstr;
}
echo msubstr($arr, 0, 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,0,1);
if(ord($temp_str) > 127)
{
$i++;
if($i<$len)
{
$new_str[]=substr($str,0,3);
$str=substr($str,3);
}
}
else
{
$new_str[]=substr($str,0,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>";
?>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  截取-字符串 php utf-8