Last active
January 8, 2016 07:27
-
-
Save wenpeng/bc7efb6fcf2465f7ede8 to your computer and use it in GitHub Desktop.
PHP截取中英文混合字符串
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 | |
if(!function_exists('sub_str')) { | |
/** | |
* 截取UTF-8编码下字符串的函数 | |
* | |
* @param string $str 被截取的字符串 | |
* @param int $length 截取的长度 | |
* @param bool $append 是否附加省略号 | |
* | |
* @return string | |
*/ | |
function sub_str($str, $length = 0, $append = true) | |
{ | |
$str = trim($str); | |
$strlength = strlen($str); | |
if ($length == 0 || $length >= $strlength) { | |
return $str; | |
} elseif ($length < 0) { | |
$length = $strlength + $length; | |
if ($length < 0) { | |
$length = $strlength; | |
} | |
} | |
if (function_exists('mb_substr')) { | |
$newstr = mb_substr($str, 0, $length, 'utf-8'); | |
} elseif (function_exists('iconv_substr')) { | |
$newstr = iconv_substr($str, 0, $length, 'utf-8'); | |
} else { | |
$newstr = substr($str, 0, $length); | |
} | |
if ($append && $str != $newstr) { | |
$newstr .= '...'; | |
} | |
return $newstr; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment