2

nl2br在显示一些保存在某处的信息时使用,但是当使用 HTML 标签时,我不想<br>为它们添加标签。

例如,如果我使用

<table>
<th></th>
</table>

它将被转换为

<table><br />
<th></th><br />
</table><br />

这为这张桌子腾出了很多空间。

何只能为其他非 HTML 内容添加换行标签?

谢谢。

4

3 回答 3

7

我也有同样的问题

我编写了这段代码,<br />在每一行的末尾添加了一个,除非该行以 html 标记结尾:

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;
}
于 2012-12-17T08:53:04.050 回答
2

您可以仅通过结束标签替换结束标签和换行符:

$str = str_replace('>
', '>', $str);
于 2011-05-24T09:11:13.827 回答
0

我认为你的问题是错误的。如果您正在输入

<table>
<th></th>
</table>

进入一个文本区域然后无论你做什么它都会包含<br />在它们之间。因为这nl2br是应该做的。

于 2011-05-24T09:11:04.823 回答