codepad
[
create a new paste
]
login
|
about
Language:
C
C++
D
Haskell
Lua
OCaml
PHP
Perl
Plain Text
Python
Ruby
Scheme
Tcl
<?php $length = 48; $strings = array( 'hello world there ok then', 'hello', 'ok then', 'this string is almost certainly longer than 48 I think', 'two words', 'three ok words', '1 2 3 4 5 6 7 8 9' ); function justify($str, $length) { $words = explode(' ',$str); if(count($words)==1) $words = array("",$str,""); $spaces = $length - array_sum(array_map("strlen", $words)); $add = (int)($spaces/(count($words) - 1)); $left = $spaces%(count($words) - 1); $spaced = implode(str_repeat("_",$add+1), array_slice($words, 0, $left + 1)); $spaced .= str_repeat("_",max(1,$add)); $spaced .= implode(str_repeat("_",max(1,$add)), array_slice($words, $left + 1)); return substr($spaced,0,$length); } foreach($strings as $string){ echo justify($string, $length)."\n"; } ?>
Private
[
?
]
Run code
Submit