Last active
November 3, 2016 06:51
-
-
Save m8rge/63c8d0897344dc2d0aa3 to your computer and use it in GitHub Desktop.
Truncate string on word break
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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