Skip to content

Instantly share code, notes, and snippets.

@m8rge
Last active November 3, 2016 06:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save m8rge/63c8d0897344dc2d0aa3 to your computer and use it in GitHub Desktop.
Save m8rge/63c8d0897344dc2d0aa3 to your computer and use it in GitHub Desktop.
Truncate string on word break
<?php
/**
* @param string $string Subject
* @param int $length Max string length
* @param bool $exactLength Truncate string with exact $length
* @param string $append Ellipsis string
* @return string
*/
class TruncateString
{
public static function truncate($string, $length, $exactLength = false, $append = '…')
{
if (mb_strlen($string) < $length) {
return $string;
}
if ($exactLength) {
return mb_substr($string, 0, $length) . $append;
} else {
$string = mb_substr($string, 0, $length);
$replaced = preg_replace("/\\s+?(\\S+)?$/u", '', $string);
return $replaced . $append;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment