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. Hey there! I know this is kinda off topic however I'd figured I'd ask. Would you be interested in exchanging links or maybe guest writing a blog article or vice-versa? My blog goes over a lot of the same subjects as yours and I feel we could greatly benefit from each other. If you might be interested feel free to shoot me an e-mail. I look forward to hearing from you! Excellent blog by the way!

    Reply
  2. Thanks for your marvelous posting! I certainly enjoyed reading it, you could be a great author. I will be sure to bookmark your blog and will eventually come back later in life. I want to encourage you continue your great work, have a nice weekend!

    Reply
  3. Hello! I know this is kinda off topic but I was wondering which blog platform are you using for this website? I'm getting tired of Wordpress because I've had issues with hackers and I'm looking at options for another platform. I would be fantastic if you could point me in the direction of a good platform.

    Reply
  4. Thanks to my father who informed me on the topic of this website, this weblog is really amazing.

    Reply
  5. Having read this I thought it was really informative. I appreciate you spending some time and energy to put this short article together. I once again find myself spending way too much time both reading and leaving comments. But so what, it was still worthwhile!

    Reply
  6. Very descriptive blog, I enjoyed that a lot. Will there be a part 2?

    Reply