Limit String Length

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

提交回复
热议问题