need help with word wrap function

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • peaforabrain
    New Member
    • Feb 2007
    • 3

    need help with word wrap function

    I've been messing about with a function to get a text block to not blow its sides.

    I need it to be 29 characters wide and 3 lines high only. I have'nt had much success with the standard php functions from php.net and have tried variations myself, but cannot get it to work.


    [PHP]
    function justify($text, $width, $break) {
    $marker = "__$%@random#$( )__";

    // lines is an array of lines containing the word-wrapped text
    $wrapped = wordwrap($text, $width, $marker);
    $lines = explode($marker , $wrapped);
    $result = "";
    foreach ($lines as $line_index=>$l ine) {
    $line = trim($line);
    $words = explode(" ", $line);
    $words = array_map("trim ", $words);
    $wordcount = count($words);
    $wordlength = strlen(implode( "", $words));
    if (3*$wordlength < 2*$width) {
    // don't touch lines shorter than 2/3 * width
    continue;
    }
    $spaces = $width - $wordlength;
    $index = 0;
    do {
    $words[$index] = $words[$index] . " ";
    $index = ($index + 1) % ($wordcount - 1);
    $spaces--;
    } while ($spaces>0);
    $lines[$line_index] = implode("", $words);
    }
    return implode($break, $lines);
    }
    [/PHP]


    This is my base code and need to modify it to only output 3 lines, no matter what.
Working...