Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
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