Laravel 截取字符串

业务中需要截取字符串长度,超出部分用...代替

方法

查询老的资料可以用str_limit($value, $limit = 100, $end = '...')来截取超出的字符串
让我们来看看该函数的源码,在 vendorlaravelframeworksrcIlluminateSupporthelpers.php 文件中的 957 行

if (! function_exists('str_limit')) {
    /**
     * Limit the number of characters in a string.
     *
     * @param  string  $value
     * @param  int     $limit
     * @param  string  $end
     * @return string
     *
     * @deprecated Str::limit() should be used directly instead. Will be removed in Laravel 6.0.
     */
    function str_limit($value, $limit = 100, $end = '...')
    {
        return Str::limit($value, $limit, $end);
    }
}

函数文档部分说明了该函数已被废弃,将在 laravel 6.0 中正式移除,推荐用
Str::limit() 替代;并且

我们来看一下源码,在 vendorlaravelframeworksrcIlluminateSupportStr.php 的 238 行

    /**
     * Limit the number of characters in a string.
     *
     * @param  string  $value
     * @param  int     $limit
     * @param  string  $end
     * @return string
     */
    public static function limit($value, $limit = 100, $end = '...')
    {
        if (mb_strwidth($value, 'UTF-8') <= $limit) {
            return $value;
        }

        return rtrim(mb_strimwidth($value, 0, $limit, '', 'UTF-8')).$end;
    }

可以看到 Str::limit() 里用的是 mb_strwidth() 来计算UTF-8编码的字符串宽度,再用 mb_strimwidth() 进行字符串宽度截取。

* 计算宽度的时候,中文算2个长度,英文算1个长度
Responses
  1. I all the time emailed this blog post page to all my associates, for the reason that if like to read it afterward my links will too.

    Reply
  2. What's up to all, how is all, I think every one is getting more from this site, and your views are good for new visitors.

    Reply
  3. thanks a lot a lot this excellent website is actually formal plus informal

    Reply
  4. Heya superb blog! Does running a blog such as this take a large amount of work? I've absolutely no knowledge of programming but I was hoping to start my own blog in the near future. Anyways, if you have any suggestions or techniques for new blog owners please share. I understand this is off subject however I just needed to ask. Thanks!

    Reply
  5. I couldn't refrain from commenting. Very well written!

    Reply
  6. You actually make it seem so easy with your presentation but I find this matter to be really something which I think I would never understand. It seems too complicated and extremely broad for me. I am looking forward for your next post, I'll try to get the hang of it!

    Reply