Created
June 16, 2012 02:18
-
-
Save ohaal/2939650 to your computer and use it in GitHub Desktop.
Justify (similar to HTML align="justify") a string, without looping
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
// Answer to http://stackoverflow.com/a/11059923/1210983 | |
function justify($str, $maxlen) { | |
$str = trim($str); | |
$strlen = strlen($str); | |
if ($strlen >= $maxlen) { | |
$str = wordwrap($str, $maxlen); | |
$str = explode("\n", $str); | |
$str = $str[0]; | |
$strlen = strlen($str); | |
} | |
$space_count = substr_count($str, ' '); | |
if ($space_count === 0) { | |
return str_pad($str, $maxlen, ' ', STR_PAD_BOTH); | |
} | |
$extra_spaces_needed = $maxlen - $strlen; | |
$total_spaces = $extra_spaces_needed + $space_count; | |
$space_string_avg_length = $total_spaces / $space_count; | |
$short_string_multiplier = floor($space_string_avg_length); | |
$long_string_multiplier = ceil($space_string_avg_length); | |
$short_fill_string = str_repeat(' ', $short_string_multiplier); | |
$long_fill_string = str_repeat(' ', $long_string_multiplier); | |
$limit = ($space_string_avg_length - $short_string_multiplier) * $space_count; | |
$words_split_by_long = explode(' ', $str, $limit+1); | |
$words_split_by_short = $words_split_by_long[$limit]; | |
$words_split_by_short = str_replace(' ', $short_fill_string, $words_split_by_short); | |
$words_split_by_long[$limit] = $words_split_by_short; | |
$result = implode($long_fill_string, $words_split_by_long); | |
return $result; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment