You're in luck, for I had the same problem, and spent half the day (and night) writing this function... it's just the type of problem that gives you nightmares trying to solve.
You can use the function like this:
wrapLines(string str, int wrap);
"str" is the string you want to have line-breaks in, and "wrap" is the maximum width allowed for a line.
Try this:
/ BEGIN /
$string = "LORD ARTHUR SAVILE'S CRIME\n\nWhen a fortune teller sees murder in the palm of Lord Arthur Savile, there is only one possible solution. Lord Arthur must fulfil his fate before he can marry his great love, the sweetly innocent Sybil.";
$string = wrapLines($string, 50);
print "<pre>$string</pre>";
/ END /
And here's the function:
function wrapLines($oldstr, $wrap)
{
$newstr = "";
$newline = "";
# Add a temporarary linebreak at the end of the $oldstr.
# We will use this to find the ending of the string.
$oldstr .= "\n";
do
{
# Use $i to point at the position of the next linebreak in $oldstr!
# If a linebreak is encountered earlier than the wrap limit, put $i there.
if (strpos($oldstr, "\n") <= $wrap)
{
$i = strpos($oldstr, "\n");
}
# Otherwise, begin at the wrap limit, and then move backwards
# until it finds a blank space where we can break the line.
else
{
$i = $wrap;
while (!ereg("[\n\t ]", substr($oldstr, $i, 1)) && $i > 0)
{
$i--;
}
}
# $i should now point at the position of the next linebreak in $oldstr!
# Extract the new line from $oldstr, including the
# linebreak/space at the end.
$newline = substr($oldstr, 0, $i+1);
# Turn the last char in the string (which is probably a blank
# space) into a linebreak.
$newline[$i] = "\n";
# Decide whether it's time to stop:
# Unless $oldstr is already empty, remove an amount of
# characters equal to the length of $newstr. In other words,
# remove the same chars that we extracted into $newline.
if ($oldstr[0] != "")
{
$oldstr = substr($oldstr, $i+1);
}
# Add $newline to $newstr.
$newstr .= $newline;
# If $oldstr has become empty now, quit. Otherwise, loop again.
} while (strlen($oldstr) > 0);
# Remove the temprary linebreak we added at the end of $oldstr.
$newstr = substr($newstr, 0, -1);
return $newstr;
}