preg_replace |正则表达式 - 仅适用于一部分

时间:2013-10-23 16:28:57

标签: php regex arrays preg-replace

我有这个代码,似乎有些不对劲,我无法正常工作。有趣的是,如果我将/§0([^§]*)/替换为/§2([^§]*)//§1([^§]*)/,则会将所选内容替换为作品,但其余部分则不然。

<?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);
?>

2 个答案:

答案 0 :(得分: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);
?>

答案 1 :(得分:0)

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

echo preg_replace(array_keys($color_code), $color_code, $text);