Limit String Length

后端 未结 10 1190
不思量自难忘°
不思量自难忘° 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:48

    $value = str_limit('This string is really really long.', 7);

    // This st...

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

    2nd argument is where to start string and 3rd argument how many characters you need to show

    $title = "This is for testing string for get limit of string This is for testing string for get limit of string This is for testing string for get limit of string This is for testing string for get limit of string";
        echo substr($title,0,50);
    
    0 讨论(0)
  • 2020-12-01 04:52

    To truncate a string provided by the maximum limit without breaking a word use this:

    /**
     * truncate a string provided by the maximum limit without breaking a word
     * @param string $str
     * @param integer $maxlen
     * @return string
     */
    public static function truncateStringWords($str, $maxlen): string
    {
        if (strlen($str) <= $maxlen) return $str;
    
        $newstr = substr($str, 0, $maxlen);
        if (substr($newstr, -1, 1) != ' ') $newstr = substr($newstr, 0, strrpos($newstr, " "));
    
        return $newstr;
    }
    
    0 讨论(0)
  • 2020-12-01 04:53

    In another way to limit a string in php and add on readmore text or like '...' using below code

    if (strlen(preg_replace('#^https?://#', '', $string)) > 30) { 
        echo substr(preg_replace('#^https?://#', '', $string), 0, 35).'&hellip;'; 
    }
    
    0 讨论(0)
提交回复
热议问题