marcwieland95
11/15/2018 - 9:28 PM

Excerpt - https://tommcfarlin.com/easily-truncate-text-in-php/

<?php
/**
 * Truncates the specified text to the specified length to the last whole word and
 * adds ellipses to the end of the truncated string.
 * 
 * @param string $text The text to truncate.
 * @param int $length The maximum allowed length of the text.
 * @return string The text if it's less than the length of the specified length or the text truncated to the specified length.
 */
public function truncate($text, $length)
{
    if ($length >= \strlen($text)) {
      return $text;
    }
  return preg_replace(
        "/^(.{1,$length})(\s.*|$)/s",
        '\\1...',
        $text
    );
}