Text
|
|
|
|
<?php
/*
This function wraps text to the given number of characters. It will only
wrap on word boundaries, and removes any resulting leading whitespace.
It also converts all whitespcae characters (tab, cr, space) to a space.
It accepts two arguments:
$text - the text to be wrapped
$wrap - the number of characters at which to wrap
It returns the wrapped text unless $text is null, then it returns void;
or $wrap is not an integer, then it returns $text untouched.
*/ function wrap_text($text, $wrap) {
if (isBlank($text)) return;
if (!is_integer($wrap)) return $text;
$text_array = explode("n", $text);
$i = $j = 0;
while ($i < sizeof($text_array)) {
$text_array[$i] = preg_replace("/s/", " ", $text_array[$i]);
$length = strlen($text_array[$i]);
if ($length <= $wrap) {
$new_text_array[$j] = $text_array[$i];
$i++;
}
else {
$tmp = substr($text_array[$i], 0, $wrap);
$spacePos = strrpos($tmp, " ");
if ($spacePos > 0) {
$new_text_array[$j] = substr($text_array[$i], 0, $spacePos+1);
$new_text_array[$j] = ltrim($new_text_array[$j]);
$text_array[$i] = substr($text_array[$i], $spacePos+1);
}
else {
$new_text_array[$j] = $tmp;
$text_array[$i] = substr($text_array[$i], $wrap);
}
}
$j++;
}
return (implode("n", $new_text_array));
}
?>
|
|
|
Usage Example
|
$string = "This is a very long string. It takes over 72 characters on a single line. It should be wrapped.n";
print $string;
print "n";
print (wrap_text($string, 72));
/* Result:
This is a very long string. It takes over 72 characters on a single line. It s
hould be wrapped.
This is a very long string. It takes over 72 characters on a single
line. It should be wrapped.
*/
|
|
|
Rate This Script
|
|
|
|