1

Minecraft 使用某些特殊字符在其客户端上用颜色格式化字符串,我想从字符串中删除这些颜色代码,但也用适当的颜色格式化字符串。颜色代码的示例是:“§1”和“§6”您可以在此处查看完整列表:http: //www.minecraftwiki.net/wiki/Formatting_codes

以下是来自客户端的原始字符串示例:“§8here is the §6message of the §8day”我需要删除“§6”颜色代码并用适当颜色的 span 标签包围文本。这是我到目前为止所拥有的,我无法弄清楚。

我希望这个结果作为一个字符串:

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

我的功能:

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;
}

谢谢!

4

2 回答 2

1

这不是那么优雅的解决方案,但它有效,更好的解决方案是使用正则表达式,但这对我来说更简单,所以享受吧。

    function spanParser($str, $htmlColor)
    {
        $str = "<span style='color:#" . $htmlColor .";'>" . $str . "</span>";
        return $str;
    }

    $exampleString = "§8here is the §6message of the §8day";
    $arrayOfChunks = explode('§', $exampleString);
    $formatedString = "";
    foreach($arrayOfChunks as $chunk)
    {
        switch($chunk[0])
        {
        case '6':
            $chunk = substr($chunk, 1);
            $formatedString = $formatedString . spanParser($chunk, "FFAA00");
            break;
        case '8':
            $chunk = substr($chunk, 1);
            $formatedString = $formatedString . spanParser($chunk, "55555");
            break;
        default:
            break;
        }
    }

    echo $formatedString;
?>
于 2013-02-13T18:49:15.530 回答
0

正则表达式的另一种解决方案:

$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 适用于 PHP 5.3 和更新版本。如果您有旧版本,您可以使用 create_function() 或用户定义的函数,而不是 preg_replace_callback() 中的匿名函数。

于 2013-02-13T19:05:56.967 回答