May 24, 2011

Using nl2br with html tags

Question by Alex Emilov

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></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.

Answer by Michiel Pater

You could replace the closing tags and newlines by only closing tags:

$str = str_replace('>
', '>', $str);

Answer by Starx

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.

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!