[ create a new paste ] login | about

Link: http://codepad.org/UXD2OECf    [ raw code | output | fork ]

PHP, pasted on Jun 16:
<?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";
}
?>


Output:
1
2
3
4
5
6
7
hello_______world_______there_______ok______then
______________________hello_____________________
ok__________________________________________then
this_string_is_almost_certainly_longer_than_48_I
two________________________________________words
three__________________ok__________________words
1_____2_____3_____4_____5_____6_____7_____8____9


Create a new paste based on this one


Comments: