Using nl2br with html tags
Asked Answered
P

3

2

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.

Peppy answered 24/5, 2011 at 9:5 Comment(2)
This is a very vague question, which amounts to "I use a function to do something to some information somewhere, but I don't want to use it under some situations." Simply don't call nl2br on those strings that you don't want new <br />s in?Delapaz
Well if I don't call it, what about the other non-html tags, they need break lines.The solution is @Michiel Pater's post.Please if you don't have any solution, don't post.How can you tell me not to use it, when I need it..Please don't post anymore..Peppy
M
2

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

$str = str_replace('>
', '>', $str);
Madriene answered 24/5, 2011 at 9:11 Comment(2)
Uh, literal newlines in such a context are horrible. Better use ">\n"Wish
heh, strange code-style :) new-line symbol can be represented by PHP_EOL constant or "\n".Proudman
I
7

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;
}
Iodate answered 17/12, 2012 at 8:53 Comment(0)
M
2

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

$str = str_replace('>
', '>', $str);
Madriene answered 24/5, 2011 at 9:11 Comment(2)
Uh, literal newlines in such a context are horrible. Better use ">\n"Wish
heh, strange code-style :) new-line symbol can be represented by PHP_EOL constant or "\n".Proudman
K
0

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.

Konstanz answered 24/5, 2011 at 9:11 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.