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. This is very interesting, You're a very skilled blogger. I've joined your feed and look forward to seeking more of your great post. Also, I have shared your web site in my social networks!

    Reply
  2. Pretty portion of content. I simply stumbled upon your webste and in accession capital to say that I acquire actually loved account your blog posts. Anyway I will be subscribing forr your feeds or even I fulfillment you get rigt of entry to consistently quickly.

    Reply
  3. This paragraph is in fact a nice one it assists new net viewers, who are wishing in favor of blogging.

    Reply
  4. Hi, its fastidious piece of writing on the topic of media print, we all understand media is a great source of information.

    Reply
  5. Have you ever thought about writing an ebook or guest authoring on other websites? I have a blog centered on the same subjects you discuss and would really like to have you share some stories/information. I know my viewers would enjoy your work. If you're even remotely interested, feel free to send me an e-mail.

    Reply
  6. [url=http://salesildenafilcitrate.com/]cheap sildenafil tablets[/url]

    Reply