PHP strlen, substr 的 UTF8 版本


在寫彩紅文字時用到了以下兩個方法.
比較簡單而且又方便的得到想要的結果.記錄一下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
function strLenByUTF8($s) {
return count(preg_split("//u", $s)) - 2;
}

function subStrByUTF8($text, $start, $limit, $encode = 'UTF-8') {
if (function_exists("mb_substri")) {
return mb_substr($text, $start, $limit, $encode);
}else{
return preg_replace(
'#^(?:[\x00-\x7F]|[\xC0-\xFF][\x80-\xBF]+){0,'.$start.'}'.'((?:[\x00-\x7F]|[\xC0-\xFF][\x80-\xBF]+){0,'.$limit.'}).*#s',
'$1',
$text
);
}
}