简体   繁体   中英

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM