Hi all,
I needed to format text to wrap at 80 characters for a program I'm writing where I need to use <PRE> inside a table. The only posts I found on this were ones suggesting <PRE> not be used, so I had to write one myself. It took embarrasingly long, but I got it working. I'm posting it here for two reasons:
1) I am a relatively new PHP programmer and therefore tend to write clumsy scripts. If you have any suggestions for optimizations or more elegants solutions, I would be glad to hear them.
2) Someone else may need to do the same thing. Maybe they can use my code.
I have tested this and it seems to work well. That said, there may be bugs I did not find.
Thanks!
<?php
function pre_format ($text, $length) // format for certain column width
{
$lines = explode("\n", $text);
$a = 0; // $new_lines tracker
$b = count($lines); // # of lines before formatting
for ($i = 0; $i < $b; $i++)
{
$cols = strlen($lines[$i]); // find length of line before formatting
if ($cols <= $length) // if not too long
{
$new_lines[$a] = $lines[$i] . "\n"; // just copy over
$a++; // increment $new_lines array
}
else // if too long
{
$temp_line = $lines[$i]; // make copy of current line
while ($cols > $length) // as long as the line is still too long
{
if ($temp_line[0] == " " && $temp_line[1] != " ") // if there is a leading space,
$temp_line = substr($temp_line, 1); // kill it
$j = $length; // go to the max length of the line
while ($temp_line[$j] != " ") // find the last space before max length
$j--;
$new_lines[$a] = substr($temp_line, 0, $j) . "\n"; // copy line-sized piece of $temp_line
// to the array of lines
$a++; // increment $new_lines array
$temp_line = substr($temp_line, $j, $cols); // chop off $temp_line what has already been added
$cols = $cols - $j; // adjust length of line
} // end while
if ($temp_line[0] == " " && $temp_line[1] != " ") // if there is a leading space,
$temp_line = substr($temp_line, 1); // kill it
$new_lines[$a] = $temp_line . "\n"; // after trimming, if shorter than $length, just copy over
$a++; // increment $new_lines array
} // end if
}
return($new_lines); // send back formatted text
}
?>