PHP - 字符串替换SyntaxError:非法字符

时间:2015-09-28 10:46:29

标签: php str-replace implode

输出$ 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 个答案:

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

答案 1 :(得分: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;

答案 2 :(得分:1)

str_replace() documentation

中有关于您的问题的重要提示
  

注意   更换订单问题

     

因为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;

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