note 49133 deleted from function.nl2br by googleguy
| From: | googleguy@php.net | Date: | Thu, 13 Jun 2013 11:01:23 +0000 |
| Subject: | note 49133 deleted from function.nl2br by googleguy | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-195148@lists.php.net to get a copy of this message | ||
Note Submitter:
----
string nl2br_indent ( string string [, mixed indent] )
This function adds break tags before newlines as nl2br and also indents the text.
If indent is not specified, string will not be indented.
<?php
function nl2br_indent($string, $indent = 0)
{
//remove carriage returns
$string = str_replace("\r", '', $string);
//convert indent to whitespaces if it is a integer.
if (is_int($indent)) {
//set indent to length of the string
$indent = str_repeat(' ', (int)$indent);
}
//replace newlines with "<br />\n$indent"
$string = str_replace("\n", "<br />\n".$indent, $string);
//add the indent to the first line too
$string = $indent.$string;
return $string;
}
?>
This is for example useful to indent text in html tags:
<?php
$str = 'Lorem ipsum dolor sit amet, consectetuer adipiscing elit.
In massa nunc, cursus eu, tincidunt in, eleifend non, enim. In ut felis. Nunc
scelerisque ante vel risus. Nulla quis metus non elit scelerisque tincidunt.'
echo '<html>'."\n";
echo ' <p>'."\n";
echo nl2br_indent($str, 4)."\n";
echo ' </p>'."\n";
echo '</html>'."\n";
?>
will return:
<html>
<p>
Lorem ipsum dolor sit amet, consectetuer adipiscing elit.<br />
In massa nunc, cursus eu, tincidunt in, eleifend non, enim. In ut felis. Nunc<br />
scelerisque ante vel risus. Nulla quis metus non elit scelerisque tincidunt.
</p>
</html>
- $str is indented by 4 spaces.