php 截取字符串(php 截取中文字符串也适用)函数

php技巧

php 截取字符串常规的截取函数是:substr(string, start int, end int);
这个substr()函数有两点说明
1.没法截取中文。
2.substr()字符串截取函数 end int参数可以超出string的实际范围,它会返回字符串最长部分,而不会有多余字符。
麻烦的中文又有gb2312,gbk,utf-8的编码分别,这样php 截取中文字符串要自己写函数
我搜索到了下面的php函数,用来截取中文字符串还是挺满意的,感谢作者,就是日子太久实在不知道谁写的了。

1
2
3
4
5
6
7
8
9
10
11
12
13
function csubstr($str, $start=0, $length, $charset="utf-8", $suffix=true) //各种编码的切割函数
{
if(function_exists("mb_substr"))
return mb_substr($str, $start, $length, $charset);
$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));
if($suffix) return "...".$slice."…";
return $slice;
}

One Response to “php 截取字符串(php 截取中文字符串也适用)函数”

  1. 冰古 Says:
    May 20th, 2008 at 9:03 pm

    可以试试mb_substr和mb_strcut,虽然可能有些服务器不支持,但内置的更快。

Leave a Reply

Icons by N.Design Studio. Designed By Ben Swift. Powered by WordPress and Free WordPress Themes
Entries RSS Comments RSS Log in