You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP中echo输出添加<b>标签不换行且修复文本顺序错乱问题

问题:BBCode转HTML后文本顺序错乱

我接触PHP仅数日,但拥有多年C++和Python开发经验,目前正在开发一款基础全局聊天系统——通过AJAX/PHP将输入的聊天内容存入MySQL数据库,每5秒以类似方式更新到指定div中。在GetChat.php中,我会在echo输出前过滤文本,尝试实现类BBCode的转换系统,但使用<b>标签或<span>标签时,文本顺序会错乱。以下是我的GetChat.php代码,以及相关效果说明,希望能得到正确实现的思路。

代码实现

<html><body>
<?php
    require_once 'dbconnection.php';
    if (!$conn) {
        die("Connection failed: " . mysqli_connect_error());
        }
    $chatarray = array();

    $qry = ('SELECT ChatText FROM Chat');
    $res = mysqli_query($conn, $qry);
    if(mysqli_num_rows($res) > 0)   // 检查结果集中是否有数据
    {
        while($row = mysqli_fetch_assoc($res))  // 遍历每一行数据
        {
            $chatarray[] = $row['ChatText'];
        }
    }

    foreach ($chatarray as $chat)
        {
        $bbcode = array("[b]", "[/b]", "[red]", "[blue]", "[/color]");
        $htmlcode = array("<b>", "</b>", "<span style='color:red'>", "<span style='color:blue'>","</span>");
        $newmessage = str_replace($bbcode, $htmlcode, $chat);

        // 将换行符转换为HTML换行标签
        $newmessage = nl2br($newmessage);

        // 按指定宽度换行
        $newmessage = wordwrap($newmessage, 34, "\n", true);

        echo $newmessage . "</br></br>";
        }
?>
</body></html>

效果说明

  • 带标签输出效果:文本顺序错乱,HTML标签与内容出现错位、混杂的情况
  • 不带标签输出效果:文本顺序正常,排版整齐无错乱
  • 数据库存储情况:聊天内容以原始BBCode格式存储,标签与内容的顺序完全正确

内容的提问来源于stack exchange,提问作者Literally Mom

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.01 20:30:23