使用 nl2br 在我的 textarea 中显示 html 标签

Joh*_*uki 3 html php nl2br

我刚开始在我的 php 站点中使用nl2br。基本上,我使用它来为“生物”字段提供一个很好的布局,以防用户按 Enter。

问题是它将确切的换行标记存储<br>在我的数据库中,当我将相同的数据从我的服务器显示到文本区域时,它也会这样做。

我如何防止 textarea 显示实际<br>标签,这是我的示例代码

//grabbing the data in the text area field
$bio = nl2br(htmlentities(trim($_POST['bio'])));

//displaying the value from the database
$row = mysql_fetch_array($my_select_query);
<textarea><?php echo $row['bio']?; ></textarea>
Run Code Online (Sandbox Code Playgroud)

我在我的 textarea 中得到了一些看起来像这样的东西 测试区结果

我怎样才能避免这种情况?

Geo*_*ton 5

您不应该nl2br(),甚至htmlentities()在将其存储到数据库之前输入。我倾向于保持合理的原始状态,这为以后更改提供了更多空间。

如果这已经在生产中,您可以创建自己的br2nl()函数来逆转以下效果nl2br()

function br2nl($input) {
    return preg_replace('/<br\\s*?\/??>/i', '', $input);
}
Run Code Online (Sandbox Code Playgroud)

  • 不仅没有必要,这会让你以后的生活更加困难! (2认同)