Last active
December 29, 2015 08:29
-
-
Save sandyUni/7643880 to your computer and use it in GitHub Desktop.
字符串截取,支持中文
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
function getStrTruncate($string, $length = 80, $etc = ''){ | |
if ($length == 0) return ''; | |
mb_internal_encoding("UTF-8"); | |
$string = str_replace("\n","",$string); | |
$strlen = mb_strwidth($string); | |
if ($strlen > $length) { | |
$etclen = mb_strwidth($etc); | |
$length = $length - $etclen; | |
$str=''; $n = 0; | |
for($i=0; $i<$length; $i++) { | |
$c = mb_substr($string, $i, 1); | |
$n += mb_strwidth($c); | |
if ($n>$length) { break; } | |
$str .= $c; | |
} | |
return $str.$etc; | |
} else { | |
return $string; | |
} | |
} | |
echo getStrTruncate("海底苍鹰博客",7); //结果是海底苍,utf8一个汉字对应二个字符 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment