Version: 1.1

Type: Function

Category: Other

License: GNU General Public License

Description: This function wraps a text at any given number of characters. It could be useful when sending email through PHP, since some people will recieve very long lines in the email body otherwise.


# Wrap lines in $oldstr at $wrap characters. Return $newstr.
function wraplines($oldstr, $wrap)
	# we expect the following things to be newlines:
	$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";
		# 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.
			$i = $wrap;
			while (!ereg("[\n\t ]", substr($oldstr, $i, 1)) && $i > 0)
		# $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.
		if ($i!=0) $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 temporary linebreak we added at the end of $oldstr.
	$newstr = substr($newstr, 0, -1);
return $newstr;

$string="LORD ARTHUR SAVILE'S CRIME\nabcdefghijklmnopqrstuvwxyz When 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.";
print "<pre>".wraplines($string,20);
print "</pre><br>";
print str_replace("\n","<br>\n",wraplines($string,20));