Stringy\Stringy::safeTruncate PHP Method

safeTruncate() public method

Truncates the string to a given length, while ensuring that it does not split words. If $substring is provided, and truncating occurs, the string is further truncated so that the substring may be appended without exceeding the desired length.
public safeTruncate ( integer $length, string $substring = '' ) : Stringy
$length integer Desired length of the truncated string
$substring string The substring to append if it can fit
return Stringy Object with the resulting $str after truncating
    public function safeTruncate($length, $substring = '')
    {
        $stringy = static::create($this->str, $this->encoding);
        if ($length >= $stringy->length()) {
            return $stringy;
        }
        // Need to further trim the string so we can append the substring
        $encoding = $stringy->encoding;
        $substringLength = \mb_strlen($substring, $encoding);
        $length = $length - $substringLength;
        $truncated = \mb_substr($stringy->str, 0, $length, $encoding);
        // If the last word was truncated
        if (mb_strpos($stringy->str, ' ', $length - 1, $encoding) != $length) {
            // Find pos of the last occurrence of a space, get up to that
            $lastPos = \mb_strrpos($truncated, ' ', 0, $encoding);
            $truncated = \mb_substr($truncated, 0, $lastPos, $encoding);
        }
        $stringy->str = $truncated . $substring;
        return $stringy;
    }