Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using nl2br with html tags

Tags:

html

php

nl2br

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.

like image 851
Alex Emilov Avatar asked Nov 20 '25 08:11

Alex Emilov


1 Answers

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;
}
like image 184
Nicolas Davoust Avatar answered Nov 21 '25 23:11

Nicolas Davoust



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!