PHP - 字符串替换语法错误:非法字符。

3

$status的输出结果

Array
(
    [1] => 1
    [2] => 0
    [3] => 0
    [4] => 4
    [5] => 4
)

$color_code_string = implode(",",$status);

输出

1,0,0,4,4

$color_code_string = str_replace("0","'#F00'",$color_code_string); 
$color_code_string = str_replace("1","'#00bcd4'",$color_code_string);
$color_code_string = str_replace("2","'#4caf50'",$color_code_string);
$color_code_string = str_replace("3","'#bdbdbd'",$color_code_string);
$color_code_string = str_replace("4","'#ff9900'",$color_code_string);

异常

SyntaxError: illegal character
colors: ['#00bcd'#ff9900'','#F00','#F00','#ff9900','#ff9900']

//prints '#00bcd'#ff9900'','#F00','#F00','#ff9900','#ff9900'

我应该如何实现以下期望输出?
'#00bcd','#ff9900','#F00','#F00','#ff9900','#ff9900'
4个回答

5
这是因为您在之前替换的颜色代码中也替换了数字。 解决方案:在合并颜色数组之前,遍历数组进行替换操作。
// Translation table, saves you separate lines of stringreplace calls.
$colorCodes = array(
  0 => "#F00",
  1 => "#00bcd4",
  2 => "#4caf50",
  3 => "#bdbdbd",
  4 => "#ff9900",
);

// Build an array of colors based on the array of status codes and the translation table.
// I'm adding the quotes here too, but that's up to you.
$statusColors = array();
foreach($status as $colorCode) {
  $statusColors[] = "'{$colorCodes[$colorCode]}'";
} 

// Last step: implode the array of colors.
$colors = implode(','$statusColors);

2
$status = [1,0,0,4,4,];
$color_code_string = implode(",",$status);
$replacements = ["0" => "'#F00'","1" => "'#00bcd4'","2" => "'#4caf50'","3" => "'#bdbdbd'","4" => "'#ff9900'",];
$color_code_string = strtr($color_code_string, $replacements); 
echo $color_code_string;

1

str_replace()文档中有一个关于你问题的重要注意事项:

注意 替换顺序问题

因为str_replace()是从左到右替换,当进行多次替换时,它可能会替换先前插入的值。请参见本文档中的示例。 使用strtr(), 因为str_replace()会覆盖先前的替换。

$status = [
    1,
    0,
    0,
    4,
    4,
];

$color_code_string = implode(",",$status);

$replacements = [
    "0" => "'#F00'",
    "1" => "'#00bcd4'",
    "2" => "'#4caf50'",
    "3" => "'#bdbdbd'",
    "4" => "'#ff9900'",
];


$color_code_string = strtr($color_code_string, $replacements); 
echo $color_code_string;

0
<?php
$color_code = array(1, 0, 0, 4, 4);

array_walk($color_code, 'color_code_replace');
$color_code_string = implode(",",$color_code);

function color_code_replace(&$cell) {
    switch ($cell) {
        case 0 : {
            $cell = '#F00';
            break;
        }
        case 1 : {
            $cell = '#00bcd4';
            break;
        }
        case 2 : {
            $cell = '#4caf50';
            break;
        }
        case 3 : {
            $cell = '#bdbdbd';
            break;
        }
        case 4 : {
            $cell = '#ff9900';
            break;
        }
        default : {
            throw new Exception("Unhandled Color Code");
        }
    }
}

var_dump($color_code);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接