Skip to content

Instantly share code, notes, and snippets.

@metelidrissi
Created March 25, 2020 14:16
Show Gist options
  • Save metelidrissi/6d6a896f4da38e8367f5c72d34c51114 to your computer and use it in GitHub Desktop.
Save metelidrissi/6d6a896f4da38e8367f5c72d34c51114 to your computer and use it in GitHub Desktop.
When you want to split long words on title's grid or list
function smart_wordwrap($string, $width = 75, $break = "\n") {
// split on problem words over the line length
$pattern = sprintf('/([^ ]{%d,})/', $width);
$output = '';
$words = preg_split($pattern, $string, -1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE);
foreach ($words as $word) {
if (false !== strpos($word, ' ')) {
// normal behaviour, rebuild the string
$output .= $word;
} else {
// work out how many characters would be on the current line
$wrapped = explode($break, wordwrap($output, $width, $break));
$count = $width - (strlen(end($wrapped)) % $width);
// fill the current line and add a break
$output .= substr($word, 0, $count) . $break;
// wrap any remaining characters from the problem word
$output .= wordwrap(substr($word, $count), $width, $break, true);
}
}
// wrap the final output
return wordwrap($output, $width, $break);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment