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条)

报告相同问题?

悬赏问题

  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路
  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应
  • ¥15 matlab基于pde算法图像修复,为什么只能对示例图像有效
  • ¥100 连续两帧图像高速减法
  • ¥15 如何绘制动力学系统的相图