gpt4 book ai didi

php - 将 nl2br 与 html 标签一起使用

转载 作者:行者123 更新时间:2023-11-28 04:25:19 24 4
gpt4 key购买 nike

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

例如如果我使用

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

它将转化为

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

这为这张 table 腾出了很多空间。

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

谢谢。

最佳答案

同样的问题,

我编写了这段代码,添加了一个 <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;
}

关于php - 将 nl2br 与 html 标签一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6108088/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com