0

我有这段代码,似乎有问题,我无法让它工作。有趣的是,如果我将/§0([^§]*)/to/§2([^§]*)//§1([^§]*)/id 替换为挑选的作品,但其余的则不然。

<?php
$text = "§6Title §f- §1Bla§2Bli§4Blu";
$color_code = array(
'/§0([^§]*)/' => '<span style="color: #000;">' . strtoupper("$1") . '</span>',
'/§1([^§]*)/' => '<span style="color: #0000AA;">' . strtoupper("$1") . '</span>',
'/§2([^§]*)/' => '<span style="color: #00AA00;">' . strtoupper("$1") . '</span>',
'/§3([^§]*)/' => '<span style="color: green;">' . strtoupper("$1") . '</span>',
'/§4([^§]*)/' => '<span style="color: green;">' . strtoupper("$1") . '</span>',
'/§5([^§]*)/' => '<span style="color: green;">' . strtoupper("$1") . '</span>',
'/§6([^§]*)/' => '<span style="color: green;">' . strtoupper("$1") . '</span>',
'/§7([^§]*)/' => '<span style="color: green;">' . strtoupper("$1") . '</span>',
'/§8([^§]*)/' => '<span style="color: green;">' . strtoupper("$1") . '</span>',
'/§9([^§]*)/' => '<span style="color: green;">' . strtoupper("$1") . '</span>',
'/§a([^§]*)/' => '<span style="color: green;">' . strtoupper("$1") . '</span>',
'/§b([^§]*)/' => '<span style="color: green;">' . strtoupper("$1") . '</span>',
'/§c([^§]*)/' => '<span style="color: green;">' . strtoupper("$1") . '</span>',
'/§d([^§]*)/' => '<span style="color: blue;">' . strtoupper("$1") . '</span>',
'/§e([^§]*)/' => '<span style="color: blue;">' . strtoupper("$1") . '</span>',
'/§f([^§]*)/' => '<span style="color: blue;">' . strtoupper("$1") . '</span>');

//echo preg_replace($suchmuster, $ersetzung, $zeichenkette);
echo $text;
echo '<br />';
echo preg_replace(key($color_code), array_shift($color_code), $text);
?>
4

2 回答 2

1

这就是我将如何进行:

<?php
$text = "§6Title §f- §1Bla§2Bli§4Blu";

$color_code = array('#000', '#0000AA', '#00AA00', 'green', 'green', 'green',
                    'green', 'green', 'green', 'green',
                    'a'=>'green', 'b'=>'green', 'c'=>'green', 'd'=>'blue',
                    'e'=>'blue', 'f'=>'blue');
$pattern = '~§([0-9a-f])([^§]*)~';
$replacement = function ($match) use ($color_code) {
    return '<span style="color: ' . $color_code[$match[1]] . '">'
         . strtoupper($match[2]) . '</span>';
};
$result = preg_replace_callback($pattern, $replacement, $text);
print_r($result);
?>
于 2013-10-23T16:57:42.657 回答
0

您必须使用数组preg_replace来替换多个值。因此,尝试使用array_keys而不是key; 并删除array_shift

echo preg_replace(array_keys($color_code), $color_code, $text);
于 2013-10-23T16:44:39.577 回答