Skip to content

Instantly share code, notes, and snippets.

@avitorio
Created April 13, 2019 11:35
Show Gist options
  • Save avitorio/5cb0dd9911e6b4d38a6f97fc986b1096 to your computer and use it in GitHub Desktop.
Save avitorio/5cb0dd9911e6b4d38a6f97fc986b1096 to your computer and use it in GitHub Desktop.
Truncate text in PHP
// 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