Using nl2br with html tags
I use nl2br
when displaying some information that is saved somewhere, but when HTML tags are used I want not to add <br>
tags for them.
For example if I use
<table>
<th></th>
</table>
it will be transformed to
<table><br />
<th>&l开发者_如何学运维t;/th><br />
</table><br />
and that makes a lot of spaces for this table.
Ho can break line tags be added only for other non-HTML content?
Thanks.
I'd the same issue,
I made this code, adding a <br />
at the end of each line except if the line finished with an html tag:
function nl2br_save_html($string)
{
if(! preg_match("#</.*>#", $string)) // avoid looping if no tags in the string.
return nl2br($string);
$string = str_replace(array("\r\n", "\r", "\n"), "\n", $string);
$lines=explode("\n", $string);
$output='';
foreach($lines as $line)
{
$line = rtrim($line);
if(! preg_match("#</?[^/<>]*>$#", $line)) // See if the line finished with has an html opening or closing tag
$line .= '<br />';
$output .= $line . "\n";
}
return $output;
}
You could replace the closing tags and newlines by only closing tags:
$str = str_replace('>
', '>', $str);
I think your question is wrong. If you are typing
<table>
<th></th>
</table>
into a text area then no matter what you do It will include <br />
in between them. Because it is what nl2br
is supposed to do.
精彩评论