Created
March 25, 2020 14:16
-
-
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
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
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
https://stackoverflow.com/questions/9815040/smarter-word-wrap-in-php-for-long-words @cmbuckley