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. Hello! Do you use Twitter? I'd like to follow you if that would be ok. I'm absolutely enjoying your blog and look forward to new posts.

    Reply
  2. There's definately a lot to know about this topic. I really like all the points you made.

    Reply
  3. I am actually happy to glance at this weblog posts which contains plenty of helpful facts, thanks for providing these kinds of data.

    Reply
  4. I feel that is among the so much significant info for me. And i'm happy reading your article. However wanna remark on few common issues, The website taste is ideal, the articles is really excellent : D. Excellent job, cheers

    Reply
  5. Nice post. I used to be checking continuously this blog and I am impressed! Extremely helpful info specifically the remaining section : ) I handle such information much. I used to be seeking this certain info for a long time. Thanks and good luck.

    Reply
  6. This is a topic that's close to my heart... Best wishes! Where are your contact details though?

    Reply