Home > php教程 > php手册 > php字符串截取函数的方法(支持中文截取 )

php字符串截取函数的方法(支持中文截取 )

PHPz
Release: 2018-10-22 15:51:58
forward
1315 people have browsed it

这篇文章主要介绍了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(&#39;mb_substr&#39;) ) {
        $newstr = mb_substr($str, 0, $length, &#39;utf-8&#39;);
    } elseif ( function_exists(&#39;iconv_substr&#39;) ) {
        $newstr = iconv_substr($str, 0, $length, &#39;utf-8&#39;);
    } else {
        //$newstr = trim_right(substr($str, 0, $length));
        $newstr = substr($str, 0, $length);
    }
    if ($append && $str != $newstr) {
        $newstr .= $append;
    }
    return $newstr;
}
Copy after login

【相关教程推荐】

1. php编程从入门到精通全套视频教程
2. php从入门到精通 
3. bootstrap教程

Related labels:
php
source:csdn.net
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template