dscpg80066 2016-12-14 11:10
浏览 226
已采纳

如何在PHP中使用<br>替换

I've tried nl2br() as well as ALL of the methods listed in the comments here. The problem I have is that even though they do insert the <br/>, the still remains in the text.

This is what I was originally doing:

<?php

$stmt = $db->prepare(...)

$stmt->execute();

while ($row = $stmt->fetch()) {

    $tldr_clean = nl2br($row['tldr']);
    $body_clean = nl2br($row['body']);

    ?>

    <section>

        <h2 class="tldr"><?= $tldr_clean ?> <?= $row['score']?>/10</h2>

        <p class="body"><?= $body_clean ?></p>

        <p class="reviewer">Written by <?= $row['name'] ?></p>

    </section>

<?php
} ?>

Assuming $row['body'] is "Hello Goodbye", the output in the html is:

Hello

Goodbye

I've tried using the method nl2br() directly with the string that is stored in the database, and it works correctly. So I'm guessing the problem is in calling the method with a variable? How can I fix it?

Edit:

String is stored as NVARCHAR2 in an SQLite table.

String stored in database:

"Fusce vitae purus tristique, efficitur dolor et, tristique ante. Aliquam sapien nisl, sagittis id justo eget, placerat ultrices nisl. In tempus sollicitudin mauris ut feugiat. Pellentesque imperdiet risus at ex dictum, sed tempus est pulvinar. Nunc nec leo fringilla diam sodales euismod sed sed odio. Cras mollis, quam at iaculis semper, justo dui maximus tellus, quis dictum urna velit sit amet justo. Curabitur consectetur fringilla arcu, sit amet ultrices est dignissim eget. Etiam non dapibus justo, et semper quam. Suspendisse tristique augue sit amet gravida euismod. Ut tempus metus quis nisl sagittis volutpat. Nam rhoncus diam luctus dictum tristique."

展开全部

  • 写回答

3条回答 默认 最新

  • dongzhan1570 2016-12-14 11:38
    关注

    If you are echo'ing the data out and you see an actual in the output, then what you have isn't not a newline character, but a literal \ followed by n character. Usually these are translated to a newline if in code, but if in string in a variable (such as when pulled from a database), it isn't. You should then do a str_replace on ' ' (notice the single quotes so it isn't translated to a newline character).

    This is likely either done by you on insert using something like addslashes (would covert a newline to \ ) or possibly done automatically by the database for some arbitrary security reason and not translated back.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部