note 55971 added to function.wordwrap
| From: | amgillet at ambivalences dot net | Date: | Fri, 19 Aug 2005 12:48:02 +0000 |
| Subject: | note 55971 added to function.wordwrap | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-93895@lists.php.net to get a copy of this message | ||
I needed a function that wraps and formats text, and adds tabs. I'm fairly OCD about how my
final code looks, and I like everything to be tab-nested, so I wrote an improved word wrap that has
the capability of adding tabs to the beginning of each line based on a tab-level parameter. I also
wanted it to never wrap on hyperlinks, since some urls can be long, and having the "<a"
and the "href=..." on separate lines makes me angry. :) It places each hyperlink and the
text inside it on its own line.
Parameters:
$string - string to wrap
$tab_level - number of tabs to prefix each line
$wrap_length - number of characters to wrap on - if this is not specified it will just wrap at each
new line, but still insert tabs
$break_string - string to break with - default "\n"
<?php
// Enhanced word wrapping function to format blocks of text.
function wrap($string, $tab_level, $wrap_length, $break_string)
{
if ($tab_level)
{
for ($i = 0; $i < $tab_level; $i++)
{
$tab .= "\t";
}
}
if ($break_string)
{
$break = $break_string . $tab;
}
else
{
$break = "\n" . $tab;
}
$string = str_replace("\r", "", $string);
if ($wrap_length)
{
$strings = preg_split("/(\n|<a [^>]+>[^<]+<\/a>)/", $string,
"", PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY );
foreach ($strings as $str)
{
if (substr($str, 0, 3) == "<a ")
{
$output .= $tab . $str . "\n";
}
elseif ($str == "\n")
{
$output .= $str;
}
else
{
$output .= $tab . wordwrap($str, $wrap_length, $break) . "\n";
}
}
}
else
{
$string = $tab . $string;
$output = str_replace("\n", $break, $string);
}
return $output;
}
?>
There may of course be a much better way to do this - if so, let me know!
----
Manual Page -- http://www.php.net/manual/en/function.wordwrap.php
Edit -- http://master.php.net/manage/user-notes.php?action=edit+55971
Delete: added to the manual -- http://master.php.net/manage/user-notes.php?action=delete+55971&report=yes&reason=added+to+the+manual
Delete: bad code -- http://master.php.net/manage/user-notes.php?action=delete+55971&report=yes&reason=bad+code
Delete: spam -- http://master.php.net/manage/user-notes.php?action=delete+55971&report=yes&reason=spam
Delete: useless -- http://master.php.net/manage/user-notes.php?action=delete+55971&report=yes&reason=useless
Delete: non-english -- http://master.php.net/manage/user-notes.php?action=delete+55971&report=yes&reason=non-english
Delete: other reasons -- http://master.php.net/manage/user-notes.php?action=delete+55971&report=yes
Reject -- http://master.php.net/manage/user-notes.php?action=reject+55971&report=yes
Search -- http://master.php.net/manage/user-notes.php