Limit String Length

后端 未结 10 1189
不思量自难忘°
不思量自难忘° 2020-12-01 03:56

I\'m looking for a way to limit a string in php and add on ... at the end if the string was too long.

相关标签:
10条回答
  • 2020-12-01 04:40

    You can use the wordwrap() function then explode on newline and take the first part, if you don't want to split words.

    $str = 'Stack Overflow is as frictionless and painless to use as we could make it.';
    $str = wordwrap($str, 28);
    $str = explode("\n", $str);
    $str = $str[0] . '...';
    

    Source: https://stackoverflow.com/a/1104329/1060423

    If you don't care about splitting words, then simply use the php substr function.

    echo substr($str, 0, 28) . '...';
    
    0 讨论(0)
  • 2020-12-01 04:41

    Do a little homework with the php online manual's string functions. You'll want to use strlen in a comparison setting, substr to cut it if you need to, and the concatenation operator with "..." or "…"

    0 讨论(0)
  • 2020-12-01 04:42

    You can use something similar to the below:

    if (strlen($str) > 10)
       $str = substr($str, 0, 7) . '...';
    
    0 讨论(0)
  • 2020-12-01 04:43
    $res = explode("\n",wordwrap('12345678910', 8, "...\n",true))[0];
    
    // $res will be  : "12345678..."
    
    0 讨论(0)
  • 2020-12-01 04:45

    From php 4.0.6 , there is a function for the exact same thing

    function mb_strimwidth can be used for your requirement

    <?php
    echo mb_strimwidth("Hello World", 0, 10, "...");
    //Hello W...
    ?>
    

    It does have more options though,here is the documentation for this mb_strimwidth

    0 讨论(0)
  • 2020-12-01 04:46

    In Laravel, there is a string util function for this, and it is implemented this way:

    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;
    }
    
    0 讨论(0)
提交回复
热议问题