-
-
Save mikemadisonweb/58b03e61a098beaf875cffa5a782db9e to your computer and use it in GitHub Desktop.
Truncate string on word break
This file contains hidden or 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