Created
April 13, 2019 11:35
-
-
Save avitorio/5cb0dd9911e6b4d38a6f97fc986b1096 to your computer and use it in GitHub Desktop.
Truncate text in PHP
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
// Taken from https://stackoverflow.com/a/79986/4187621 | |
function tokenTruncate($string, $your_desired_width) { | |
$parts = preg_split('/([\s\n\r]+)/u', $string, null, PREG_SPLIT_DELIM_CAPTURE); | |
$parts_count = count($parts); | |
$length = 0; | |
$last_part = 0; | |
for (; $last_part < $parts_count; ++$last_part) { | |
$length += strlen($parts[$last_part]); | |
if ($length > $your_desired_width) { break; } | |
} | |
return trim(implode(array_slice($parts, 0, $last_part))); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment