dsnrixf6765 2013-02-13 16:49
浏览 73
已采纳

PHP格式化字符串以删除特殊字符颜色代码并添加适当的颜色

Minecraft uses certain special characters to format strings with colors on their client, and I want to remove those color codes from the string but also format the string with the appropriate colors. An example of the color codes are: '§1' and '§6' You can see the full list here: http://www.minecraftwiki.net/wiki/Formatting_codes

Here is an example of my string raw from the client: "§8here is the §6message of the §8day" I need to remove the '§6' color code and surround the text with span tags with the appropriate color. Here is what I have so far, and I cannot figure this out.

I would want this result as a string:

<span style='color:#55555;'>here is the </span><span style='color:#FFAA00;'> message of the</span><span style='color:#55555;'> day</span>

My function:

function formatMOTD($motd) {
$result = array();
$previous;

$result = split("§1", $motd);
if (!empty($result)) {
    foreach ($result as $value) {
        $previous .= "<span style='color:#0000AA;'>" . substr($value, 1) . "</span>";
    }
}
$result = split("§8", $motd);
if (!empty($result)) {
    foreach ($result as $value) {
        $previous .= "<span style='color:#55555;'>" . substr($value, 1) . "</span>";
    }
}
$result = split("§6", $motd);
if (!empty($result)) {
    foreach ($result as $value) {
        $previous .= "<span style='color:#FFAA00;'>" . substr($value, 1) . "</span>";
    }
}

$motd = $previous;
return $motd;
}

thanks!

  • 写回答

2条回答 默认 最新

  • dream0614 2013-02-13 19:05
    关注

    Another solution with regex:

    $txt = "test §8here is the §6message of the §8day";
    echo preg_replace_callback('/§(\d+)([^§]*)/s', 
        function($match)
        {
            $color = '';
            switch($match[1]) {
                case '1': 
                    $color = '0000AA';
                    break;
                case '6': 
                    $color = 'FFAA00';
                    break;
                case '8': 
                    $color = '555555';
                    break;
                default:
                    break;
            }
            return "<span style='color:#" . $color .";'>" . $match[2] . "</span>";
        },
        $txt);
    

    UPD For PHP 5.3 and newer. If you have an older version you can use create_function() or user defined function instead of anonymous one inside the preg_replace_callback().

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

报告相同问题?

悬赏问题

  • ¥500 52810做蓝牙接受端
  • ¥15 基于PLC的三轴机械手程序
  • ¥15 多址通信方式的抗噪声性能和系统容量对比
  • ¥15 winform的chart曲线生成时有凸起
  • ¥15 msix packaging tool打包问题
  • ¥15 finalshell节点的搭建代码和那个端口代码教程
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录