php字符串截取函数,支持中文截取

简介:
/** * 基于PHP的 mb_substr,iconv_substr 这两个扩展来截取字符串,中文字符都是按 1 个字符长度计算; * 该函数仅适用于utf- 8 编码的中文字符串。 * * @ param $str 原始字符串 * @ param $length 截取的字符数 * @ param $append 替换截掉部分的结尾字符串 * @ return 返回截取后的字符串 */ function sub_str( $str , $length = 0 , $append = '...' ) { $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 = trim_right(substr( $str , 0 , $length )); $newstr = substr( $str , 0 , $length ); } if ( $append && $str != $newstr ) { $newstr .= $append ; } return $newstr ; }




本文转自TBHacker博客园博客,原文链接:本文转自TBHacker博客园博客,原文链接:xxxxx,如需转载请自行联系原作者,如需转载请自行联系原作者


相关文章
|
1月前
|
JSON JavaScript PHP
PHP把unicode编码的json字符串转中文
PHP把unicode编码的json字符串转中文
13 0
|
2月前
|
PHP
从建站到拿站 -- PHP判断循环及函数
从建站到拿站 -- PHP判断循环及函数
12 0
|
2月前
|
PHP
从PHP开始学渗透 -- 函数
从PHP开始学渗透 -- 函数
8 0
php案例:判断这个是繁体字还是简体字(满足绝大部分字符)用php函数
php案例:判断这个是繁体字还是简体字(满足绝大部分字符)用php函数
php案例:判断这个是繁体字还是简体字(满足绝大部分字符)用php函数
|
3月前
|
Shell PHP
php案例:截取sy.66969.cn/sh.html中的sh怎么做?
php案例:截取sy.66969.cn/sh.html中的sh怎么做?
php案例:截取sy.66969.cn/sh.html中的sh怎么做?
|
3月前
|
PHP 数据安全/隐私保护